抱歉这个奇怪的主题,但我不知道如何以另一种方式表达它.
我正在尝试从调用类访问一个方法.就像在这个例子中:
class normalClass {
public function someMethod() {
[...]
//this method shall access the doSomething method from superClass
}
}
class superClass {
public function __construct() {
$inst = new normalClass;
$inst->someMethod();
}
public function doSomething() {
//this method shall be be accessed by domeMethod form normalClass
}
}
这两个类都不依赖于继承,我不想将该函数设置为static.
有没有办法实现这一目标?
谢谢你的帮助!
您可以像这样传递对第一个对象的引用:
class normalClass {
protected $superObject;
public function __construct(superClass $obj) {
$this->superObject = $obj;
}
public function someMethod() {
//this method shall access the doSomething method from superClass
$this->superObject->doSomething();
}
}
class superClass {
public function __construct() {
//provide normalClass with a reference to ourself
$inst = new normalClass($this);
$inst->someMethod();
}
public function doSomething() {
//this method shall be be accessed by domeMethod form normalClass
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以为此使用 debug_backtrace() 。它有点不确定,但出于调试目的它很有用。
class normalClass {
public function someMethod() {
$trace = debug_backtrace();
$trace[1]['object']->doSomething();
}
Run Code Online (Sandbox Code Playgroud)
}