对那个奇怪的话题感到抱歉,但我不知道该如何用其他方式表达它。
我正在尝试从调用类访问方法。像这个例子一样:
class normalClass {
公共(public)功能someMethod(){
[...]
//此方法应从superClass访问doSomething方法
}
}
class superClass {
公共(public)功能__construct(){
$ inst =新的normalClass;
$ inst-> someMethod();
}
公共(public)功能doSomething(){
//此方法应由domeMethod形式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
}
}
关于PHP类: get access to the calling instance from the called method,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1093101/