在我的代码中,我有两个类 - 第一个"Foo"启动第二个"Bar"...我想做的是找到一些使用父级函数和变量的方法。
class Bar {
function __construct() {
/*
* From within this function, how do I access either the returnName() function
* OR the $this -> name variable from the class above this?
* The result being:
*/
$this -> name = parent::returnName();
$this -> else = parent -> name;
}
}
class Foo {
function __construct() {
$this -> name = 'Fred';
$this -> var = new Bar();
}
function returnName() {
return $this -> name;
}
}
$salad = new Foo();
我意识到"父"的语法是指实现或扩展,但是可以使用这种方法吗?
您可以在 Bar
的构造函数中注入 $this
(Foo 类)
<?php
class Bar {
function __construct($fooClass) {
/*
* From within this function, how do I access either the returnName() function
* OR the $this -> name variable from the class above this?
* The result being:
*/
$this -> name = $fooClass->returnName();
$this -> else = $fooClass -> name;
}
}
class Foo {
function __construct() {
$this -> name = 'Fred';
$this -> var = new Bar($this);
}
function returnName() {
return $this -> name;
}
}
$salad = new Foo();
小心
处理
这不是100%干净的解决方案,但会起作用。您的代码应有很好的文档记录,以避免将来的混淆。
有一个非常酷的函数叫做debug_backtrace()
它为您提供有关为获取此函数而进行的所有调用的信息,包括文件名、调用的行、被调用的函数、类和对象名称以及参数。
以下是如何使用它:
class Bar {
function __construct() {
//get backtrace info
$trace = debug_backtrace();
//get the object from the function that called class
//and call the returnName() function
$this->name = $trace[1]['object']->returnName();
echo $this->name;
//want more info about backtrace? use print_r($trace);
}
}
class Foo {
function __construct() {
$this -> name = 'Fred';
$this -> var = new Bar();
}
function returnName() {
return $this -> name;
}
}
$salad = new Foo();
结果:
佛瑞德