PHP parent ::对象的等价物

时间:2012-08-06 11:02:40

标签: php oop

class Second
{
  // i've got to access to $variable from First instance from here
}

class First
{
  public $variable;
  public $SecondInstance;

  public function __construct($variable) 
  {
    $this->variable = $variable;
    $this->SecondInstance = new Second();
  }
}
 $FirstObj = new First('example variable');

我需要对象的父:: $变量的等价物。

是否有可能以这种方式做到这一点?

3 个答案:

答案 0 :(得分:0)

不,你不能。你可以管理它的唯一方法是在没有扩展First的情况下将“$ this”传递给Second的构造函数:

$this->SecondInstance = new Second ($this);

或者,您可以简单地将$变量传递给它的构造函数。

答案 1 :(得分:0)

你的意思就像PHP中的parent函数:

//You may find yourself writing code that refers to variables 
//and functions in base classes. This is particularly true if 
// your derived class is a refinement or specialisation of 
//code in your base class.

//Instead of using the literal name of the base class in your 
//code, you should be using the special name parent, which refers 
//to the name of your base class as given in the extends declaration 
//of your class. By doing this, you avoid using the name of your base 
//class in more than one place. Should your inheritance tree change 
//during implementation, the change is easily made by simply 
//changing the extends declaration of your class. 


<?php
class A {
    function example() {
    echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
    echo "I am B::example() and provide additional functionality.<br />\n";
    parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>

答案 2 :(得分:0)

我建议你稍微改变你的结构“延伸”:

class second extends first{
    public __construct(){
        parent::__construct();
        echo $this->variable;
    }
}

否则你需要在第二个变量中将“first”指定为父类,并实际访问它:

class second{
    public $first;
    public function __construct($first){
        $this->first = $first;
        var_dump($this->first->variable);
    }
}

当然,您也可以将第一个类设为静态并以此方式访问它。