2016-09-07 44 views
-4

我需要在類的構造函數中增加一個數字,而不調用靜態函數。我的代碼如下:php在靜態構造函數中增加一個數字

class Addup { 

static public $num; 

function __construct($num) { 
    echo 'My number is==>' . $num; 
    static::$num++; 
    } 
} 

$inc = new Addup();//instantiated an object 
echo '<br>'; 
echo $inc::$num;//should be 2, but still 1, should it be $inc = new  Addup() or $inc->addup() implemented in my class? 
echo '<br>'; 
echo $inc::$num;//should be 3, but still 1 
echo '<br>'; 
echo $inc::$num;//should be 4, but still 1 

任何想法將受到歡迎,謝謝

UPD作了如下的重構:

$inc = new Increment();//My number is==>2 
echo '<br>'; 
$inc = new Increment();//My number is==>3 
echo '<br>'; 
$inc = new Increment();//My number is==>4 
echo '<br>'; 
$inc = new Increment();//My number is==>5 

這是要做到這一點,而不調用的唯一途徑在課堂上的功能?

+3

參數'回聲$ INC :: $ #這不會調用構造函數。 –

+0

爲什麼一個stacti屬性? – cmnardi

+0

每次我需要增加數字時,是否需要調用新的(Addup),或者我可以做其他事情? – Masha

回答

2

靜態屬性意味着靜態屬性的值在類的多個實例化中將是相同的。

這可能證明什麼用您的代碼比你的例子

旁註更好發生的事情:你是通過對東西沒有效果,是無爲

<?php 
class Addup { 

    static public $num; 

    function __construct() { 
     static::$num++; 
    } 
} 

$inc1 = new Addup(); // calls the constructor therefore +1 
echo PHP_EOL; 
echo $inc1::$num; // 1 

$inc2 = new Addup(); // calls the constructor therefore +1 
echo PHP_EOL; 
echo $inc2::$num; // 2 

$inc3 = new Addup(); // calls the constructor therefore +1 
echo PHP_EOL; 
echo $inc3::$num; // 3 

// now if you look at $inc1::$num; after instantiating inc2 and inc3 
echo PHP_EOL; 
echo $inc1::$num; // NOT 1 but whatever it was last incremented to i.e. 3