2012-04-08 79 views
0

我試圖使用靜態方法(我不想實例化一個類)。 我把這個例子。PHP中類的靜態方法/函數

<?php 
    class RootClass { 
    const Member = 20; 
    public static function Member() { 
     return self::Member; 
    } 
    } 

    class NewClass { 
    private $ValNewClass = ""; 
    private function InitNewClass() { 
     $this->ValNewClass = RootClass::Member(); 
    } 
    public static function GetNewVal() { 
     $this->InitNewClass(); 
     $Validation = true; 
     if ($this->ValNewClass>10){ 
     echo "greater than 10"; 
     $Validation = false; 
     } else { 
     echo "Not greater than 10"; 
     } 
     return $Validation; 
    } 
    } 
    $Val2 = NewClass::GetNewVal(); //It must print "greater than 10" 
?> 

我需要知道我的錯誤在哪裏。 這不是真正的代碼,只是簡單的詢問形式。

謝謝。

+1

爲什麼'$ this'在這裏:'$ this-> InitNewClass();'? – 2012-04-08 04:08:22

+0

作爲一個方面說明,使用適當的命名約定,ALL_CAPS用於常量,lower_case()或camelCase()用於函數名稱和$變量,First_letter_uppercased用於類名稱。 – 2012-04-08 11:24:23

+0

你不能使用'$ this'是靜態方法,把它改爲'self' – rdo 2012-04-08 12:46:40

回答

0
<?php 
    class Rootclass { 
    const MEMBER = 20; 
    public static function member() { 
     return self::MEMBER; 
    } 
    } 

    class Newclass { 
    private static $valnewclass = ""; 
    private function initnewclass() { 
     self::$valnewclass = Rootclass::member(); 
    } 
    public static function getnewval() { 
     self::initnewclass(); //Initialice Val for make comparation 
     $validation = true; 
     if (self::$valnewclass>10){ 
     echo "<br>greater than 10"; 
     $Validation = false; 
     } else { 
     echo "<br>Not greater than 10"; 
     } 
     return $validation; 
    } 
    } 
    $Val2 = Newclass::getnewval(); //It must print "greater than 10" 
    echo "<br>After"; 
?> 

謝謝 的代碼工作。

Chepe。

0

在PHP中,$ this變量在聲明爲靜態的方法內不可用。

0

您不能在靜態方法內引用非靜態字段。這種分類中的值不能是對象依賴的。當你使用$ this-> field時,你引用了類的實例中的值。如果你想修改靜態字段,你應該使用self :: field。