我有一个类,a(),方法为a1()。在a1()中,我实例化类b(),如何使其能够访问a()中的所有公共变量和方法?不扩展它。类b()是我在几个位置使用的类,但我希望b()能够访问实例化它的类。另一种选择是实例化并将所有变量和内容传递到其中,但这看起来相当丑陋,而且不够灵活。
class a{
var $test = 'yes'; // I want b() to be able to reach all public stuff in a()
private $b;
public function a1(){
$this->b = new b();
$this->b->b1();
}
}
class b{
public function b1(){
echo $this->test; // Should echo 'yes'
}
}
$temp = new a();
$temp->a1(); // Should echo 'yes'
根据注释,在不扩展的情况下将数据从一个类外推到另一个类的唯一其他方法是使用反射。
我可以详细介绍,但一个例子说了1000个单词。http://php.net/manual/en/reflectionclass.getproperties.php
如果使用得当,反射会变得非常强大。然而,我想说这是一种没有的情况,我建议重组你的类,也许一个很好的方法是使用特性。简单地说;将粘贴方法复制到类中。
您也可以将类作为参数传递,但它的用法会略有变化。
class a{
public $test = 'yes'; // I want b() to be able to reach all public stuff in a()
public $b;
public function __construct(){
$this->b = new b($this);
}
}
class b{
private $instance;
public function b1(){
echo $this->instance->test; // Should echo 'yes'
}
public function __construct($instance){
if($instance instanceof a){
$this->instance = $instance;
} else {
echo "argument is not a member of 'a'";
}
}
}
$temp = new a();
$temp->b->b1(); // Should echo 'yes'
?>
<?php
class a{
var $test = 'yes'; // I want b() to be able to reach all public stuff in a()
protected $b;
public function a1(){
$this->b = new b($this);
$this->b->b1();
}
}
class b{
private $_parent = null;
public function __construct($parent) {
$this->_parent = $parent;
}
public function b1() {
echo $this->_parent->test; // Should echo 'yes'
}
}
$temp = new a();
$temp->a1(); // Should echo 'yes'