PHP类:从被调用方法访问调用实例 [英] PHP Classes: get access to the calling instance from the called method
本文介绍了PHP类:从被调用方法访问调用实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对不起这个奇怪的主题,但我不知道该如何用其他方式表达.
sorry for that weird subject but I don't know how to express it in an other way.
我正在尝试从调用类访问方法.像本例一样:
I'm trying to access a method from a calling class. Like in this example:
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
}
}
两个类都不通过继承关联,我不想将函数设置为静态.
Both classes are not related by inheritance and I don't want to set the function to static.
有什么方法可以实现?
感谢您的帮助!
推荐答案
您可以像这样将引用传递给第一个对象:
You can pass a reference to the first object like this:
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类:从被调用方法访问调用实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文