1
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');

オブジェクトのparent::$variableに相当するものが必要です。

その方法でそれを行う可能性はありますか?

4

3 に答える 3

0

いいえ、あなたがすることはできません。First を拡張せずにそれを管理できる唯一の方法は、"$this" を Second のコンストラクターに渡すことです。

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

または、単純に $variable をそのコンストラクターに渡すことができます。

于 2012-08-06T11:05:55.867 に答える
0

PHPの関数のように意味します:

//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();
?>
于 2012-08-06T11:07:15.510 に答える