2017-09-23 144 views
0

我不太瞭解class和他們的member variables。 我的疑問是,我們可以在同一個類中聲明並初始化另一個成員變量的成員變量嗎?我們可以聲明和初始化一個成員變量在同一類

這樣

class newClass { 
    private $variable1 = 'new1'; 
    private $variable2 = $variable1.'new2'; 
} 

如果不能,請幫我找到這個解決方案的。 如果這是一個錯誤的問題,請原諒我。

回答

2

始終在構造函數中初始化成員變量。您可以在構造函數中分配動態值。 試試這個代碼:

<?php 
class newClass { 
    private $variable1 ; 
    private $variable2; 
    function __construct() 
    { 
     $this->variable1 = 'new1'; 
     $this->variable2 = $this->variable1.'new2'; 
    } 
    function get_data() 
    { 
     echo "var1= ".$this->variable1; 
     echo "<br>"; 
     echo "var2= ".$this->variable2; 
    } 
} 
$obj = new newClass(); 
$obj->get_data(); 
4

不,你不能這樣做。

你可以做的反而是做初始化在構造函數中:

class Foo 
{ 
    private $a = 'something'; 
    private $b; 

    public function __construct() 
    { 
     $this->b = $this->a . 'foobar'; 

    } 
} 

Buuuut,這實際上是一個有點可疑的做法,因爲它,你應該儘量避免這樣做在構造任何計算,因爲你放棄了實際測試邏輯部分的能力(因爲構造函數總是被執行,你無法比較前後狀態)。

一個更好的辦法是離開這個邏輯在吸氣的方法:

class Foo 
{ 
    const DEFAULT_VALUE = 'lorem ipsum'; 
    const DEFAULT_PREFIX = '_'; 

    private $bar; 

    public function __construct(string $bar = self::DEFAULT_VALUE) 
    { 
     $this->bar = $bar; 
    } 


    public function getPrefixedBar(string $prefix = self::DEFAULT_PREFIX) 
    { 
     return $prefix . $this->bar; 
    } 
} 

有了這個代碼,你會得到:

$a = new Foo; 
echo $a->getPrefixedBar(); // shows: '_lorem ipsum'; 
echo $a->getPrefixedBar('test '); // shows: 'test lorem ipsum'; 

$b = new Foo('xx'); 
echo $b->getPrefixedBar(); // shows: '_xx'; 
+2

這應該是公認的答案 – Akintunde007