【发布时间】:2012-08-02 09:05:35
【问题描述】:
我知道这是一直在做的,但出于某种原因,这对我来说一点意义都没有。 [插入@#$%!这里]我不知道这个(假设)明显的解决方案的正确 OOP 过程是什么。我已经简要阅读了 Abstract 和 Interface 类型类,但对任何符合我要求的示例均无济于事。
所以这里是设置...
在此示例中,我有两个类,一个将从我的脚本中调用,另外两个可以从我的脚本中调用,也可以从我调用的第一个类中调用。伪代码:
<?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();。
那么,女士们,先生们,解决方案是什么?谢谢!
【问题讨论】:
-
我不明白这个问题。 究竟你想用这个来完成什么? (有时英文比代码更容易阅读
:)) -
您的伪代码有一个全局变量
$timer,您正试图将其用作局部变量。在本地创建$timer或使用global $timer;。 -
@minitech,哈,我听到了...所以基本上,我希望能够从另一个单独的类函数中调用一个类函数。
-
@Vatev,让我确保我没有弄乱我的假... 编辑:你是对的,如果我愿意,我可以这样做。不过,这对我来说似乎不是正确的编码。
-
当你说assumingly时,你的意思是presumably吗?