我正在尝试从调用类访问方法。就像在这个例子中一样:
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。
有没有办法实现这个目标?
感谢您的帮助!
答案 0 :(得分:5)
您可以像这样传递对第一个对象的引用:
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
}
}
答案 1 :(得分:1)
您有几个选择。您可以像这样使用聚合
class normalClass
{
protected $superClass;
public function __construct( superClass $superClass )
{
$this->superClass = $superClass;
}
public function someMethod()
{
$this->superClass->doSomething();
}
}
class superClass
{
public function __construct()
{
$inst = new normalClass( $this );
$inst->someMethod();
}
public function doSomething()
{ //this method shall be be accessed by domeMethod form normalClass
}
}
或者只是一个直接的制定者
class normalClass
{
protected $superClass;
public function setSuperClass( superClass $superClass )
{
$this->superClass = $superClass;
}
public function someMethod()
{
if ( !isset( $this->superClass ) )
{
throw new Exception( 'you must set a superclass' );
}
$this->superClass->doSomething();
}
}
class superClass
{
public function __construct()
{
$inst = new normalClass();
$inst->setSuperClass( $this );
$inst->someMethod();
}
public function doSomething()
{ //this method shall be be accessed by domeMethod form normalClass
}
}
答案 2 :(得分:1)
您可以使用debug_backtrace()。它有点不确定,但出于调试目的,它很有用。
class normalClass {
public function someMethod() {
$trace = debug_backtrace();
$trace[1]->object->doSomething();
}
}
答案 3 :(得分:0)
根据您的使用情况,您可能希望仅将实例传递给该函数:
class normalClass {
public function someMethod($object) {
$object->doSomething();
}
}
如果normalClass::someMethod()
可由多个不同的$object
调用,则这可能是更好的选择(而不是将$object
提供给整个normalClass实例)。
但无论如何,您可以考虑创建一个用于type hinting的接口:
interface ISomethingDoer {
public function doSomething();
}
class normalClass {
public function someMethod(ISomethingDoer $object) {
# Now PHP will generate an error if an $object is passed
# to this function which does not implement the above interface.
// ...
class superClass implements ISomethingDoer {
// ...
答案 4 :(得分:0)
woah我遇到了和你相同的问题,但是没有用这么简单的传递对象的引用,我去了一个事件管理器,基本上,当普通类中发生某些事情时,它会触发一个事件,被一个类监听,并且所述类(监听器)将调用超类来执行该功能,并在必要时传递新的参数。
无论如何,无论您将它作为参数传递给对象还是采用基于事件的方法,两种解决方案都能正常工作。选择你喜欢的那个。
有关活动的更多信息,同情解释说它非常好。 http://symfony.com/doc/current/components/event_dispatcher/introduction.html