2016-09-12 8 views
1

私はApplicationクラスを持っていますが、私はそれを拡張する多くの別々のクラスも持っています。親のApplicationクラスに$variableを設定した場合、その子で自動的に利用できるようにするにはどうすればよいですか?クラスの変数を自動的にその子クラスで使用できるようにするにはどうすればよいですか?

class Application { 
    public $variable; 

    public function __construct() { 
     $this->variable = "Something"; 
    } 
} 

class Child extends Application { 
    public function doSomthing() { 
    $mything = $variable." is cool"; 
    return $mything; 
    } 
} 

私は私のdoSomthing()方法でglobal $variable;を置くことができます知っているが、それは私が書くあらゆる方法で何度も行うことが超面倒です。私のすべての子クラスのメソッドで利用できる方法はありますか?おかげさまで

+1

ただ、 'ます$ this-> variable' – gmsantos

+0

を使用しますが、試してみます親宣言? [parent ::](http://php.net/manual/en/keyword.parent.php) –

答えて

1

メソッドのApplicationクラスに、variableという名前のプロパティを設定するだけです。

プロパティvisibility permits(例えば、パブリックまたは保護されている)場合は、$this->potatoで任意の子クラスメソッドでプロパティpotatoにアクセスすることができます。

class Application { 
    public $variable; 

    public function __construct() { 
     $this->variable = "Something"; 
    } 
} 

class Child extends Application { 
    public function doSomthing() { 
    $mything = $this->variable." is cool"; 
    return $mything; 
    } 
} 
関連する問題