我知道这一直都在做,但出于某种原因,这对我来说一点意义都没有。[插入@#$%!此处]我不知道对于这个(假设)显而易见的解决方案,合适的OOP过程是什么。我简要地阅读了抽象和接口类型的类,但没有任何示例可以满足我的要求。
这是设置。。。
在本例中,我有两个类,一个将从脚本中调用,另两个可以从脚本中或从我调用的第一个类中调用。psuedo代码:
<?php
// Some code here
$timer = new timer();
$doSomethingCool = new doSomethingCool();
$doSomethingCool->doIt();
print $timer->length();
class timer {
private $startTime;
private $stopTime;
private $length;
public function start() {
// Start running the timer
}
public function end() {
// End the timer
}
public function length() {
// Return the length of the timer
return $this->length;
}
}
class doSomethingCool {
public function doIt() {
$timer->start();
// Some code here
$timer->end();
}
}
?>
我已经能够让它"运行"(见下文),但这项工作很混乱,我100%确信这不是合适的面向对象建模:
<?php
// Start by declaring all classes and pass all classes to themselves...
$doSomethingCool = new doSomethingCool();
$timer = new timer();
$class = array(
'doSomethingCool'=>$doSomethingCool,
'timer'=>$timer
);
$doSomethingCool->class = $class;
$timer->class = $class;
// Some code here
$class['doSomethingCool']->doIt();
print $timer->length();
class timer {
// In each class we now declare a public variable
// 'class' that we had passed all class instances to...
public $class;
private $startTime;
private $stopTime;
private $length;
public function start() {
// Start running the timer
}
public function end() {
// End the timer
}
public function length() {
// Return the length of the timer
return $this->length;
}
}
class doSomethingCool {
public $class;
public function doIt() {
$this->class['timer']->start();
// Some code here
$this->class['timer']->end();
}
}
?>
由于E_STRICT,我不想使用$timer::start();
。
那么,解决方案是什么呢,女士们,先生们?谢谢
我认为您想将其他类注入到某个类中。如果是:
class Database {}
class Timer {}
class Foo
{
protected $database;
protected $timer;
public function __construct(Database $database, Timer $timer)
{
$this->database = $database;
$this->timer = $timer;
}
public function doSomething()
{
$this->timer->start();
}
}
$database = new Database();
$timer = new Timer();
$foo = new Foo($database, $timer);
请注意,您当然应该添加真正的类(我使用过Database
和Timer
)。
多态方式:
class SomeClass {
protected $db;
function __construct(Database $database) {
$this->db = $database;
}
function doIt() {
// . . .
}
}
class TimedSomeClass extends SomeClass {
protected $timer;
function __construct(Database $db, Timer $timer) {
$this->timer = $timer;
parent::__construct($db);
}
function doIt() {
$this->timer->start();
parent::doIt();
$this->timer->stop();
}
}
多态性可能不是解决这种情况的最佳工具,但听起来你想在你的问题中用多态性来做这件事,所以它就在这里。
如果您希望类a的对象a访问类b的对象
b,那么如果
b在某种意义上不是全局的,则必须将其传递给
a。在你的情况下,你可以这样做:
- 通过将其添加到构造函数
new doSomethingCool($timer)
或 - 通过创建和使用set方法,并将对象句柄存储为私有属性,例如
$doSomethingCool->setTimer( $timer );
或 - 通过在
doIt()
中作为参数传递
另一种选择是为计时器类使用一个单例模板——这本质上使计时器成为一个glbal对象,但现在通常不赞成使用这种模板。