2012-04-07 63 views
0

我需要用父類的子類創建一個變量。 實施例:如何在PHP5的子類中創建一個變量

父類

<?php 
class parentClass 
{ 
    function __construct() 
    { 

     $subClass = new subClass(); 
     $subClass->newVariable = true; 

     call_user_func_array(array($subClass , 'now') , array()); 

    } 
} 
?> 

子類

<?php 
class subClass extends parentClass 
{ 
    public function now() 
    { 
     if($this->newVariable) 
     { 
      echo "Feel Good!!!"; 
     }else{ 
      echo "Feel Bad!!"; 
     } 
     echo false; 
    } 
} 
?> 

執行父類

<?php 
$parentClass = new parentClass(); 
?> 

目前

公告:未定義的屬性:子類:: $ newVariable在subclass.php上 線6

我真的需要這樣:

感覺良好!

解決方案:

<?php 
class parentClass 
{ 
    public $newVariable = false; 

    function __construct() 
    { 

     $subClass = new subClass(); 
     $subClass->newVariable = true; 

     call_user_func_array(array($subClass , 'now') , array()); 

    } 
} 
?> 

<?php 
class subClass extends parentClass 
{ 
    public function now() 
    { 
     if($this->newVariable) 
     { 
      echo "Feel Good!!!"; 
     }else{ 
      echo "Feel Bad!!"; 
     } 
     echo false; 
    } 
} 
?> 
+2

'var $ newVariable' in subclass? – 2012-04-07 03:11:19

+0

@ eicto,我需要創建一個新的變量。看代碼...謝謝! – 2012-04-07 03:13:27

+1

我現在看到代碼,它看起來無限循環,不是嗎? – 2012-04-07 03:14:22

回答

4

您必須聲明子類中的屬性:

<?php 
class subClass extends parentClass 
{ 
    public $newVariable; 

    public function now() 
    { 
        if($this->newVariable) 
        { 
            echo "Feel Good!!!"; 
        }else{ 
            echo "Feel Bad!!"; 
        } 
        echo false; 
    } 
} 
?> 

編輯

這是不是說,或使用magic methods,這不是很優雅,並且可以使你的代碼難以調試。

相關問題