2010-12-19 61 views
2

在PHP中,有使用oophp,方法和屬性命名

$myClass::method() 

$myClass->method() 

什麼是對變化的原因有什麼區別? (我相信->已經存在了更長的時間。)

我可以看到使用方法::和使用->的性質,反之亦然。

+0

參見這裏:http://stackoverflow.com/q/4361598/50079 – Jon 2010-12-20 00:07:54

回答

6

::是範圍解析運算符,用於訪問類的成員static

->是成員操作符,用於訪問對象的成員。

下面是一個例子:

class Car { 
    public $mileage, $current_speed, $make, $model, $year; 
    public function getCarInformation() { 
     $output = 'Mileage: ' . $this->mileage; 
     $output = 'Speed: ' . $this->current_speed; 
     $output = 'Make: ' . $this->make; 
     $output = 'Model: ' . $this->model; 
     $output = 'Year: ' . $this->year; 
     return $output; 
    } 
} 

class CarFactory { 

    private static $numberOfCars = 0; 

    public static function carCount() { 
     return self::$numberOfCars;  
    } 

    public static function createCar() { 
     self::$numberOfCars++; 
     return new Car(); 
    } 

}  

echo CarFactory::carCount(); //0 

$car = CarFactory::createCar(); 

echo CarFactory::carCount(); //1 

$car->year = 2010; 
$car->mileage = 0; 
$car->model = "Corvette"; 
$car->make = "Chevrolet"; 

echo $car->getCarInformation(); 
+1

你應該添加一個非靜態方法來顯示差異 – pastjean 2010-12-20 00:06:05

+1

PHP稱它爲一個Paamayim Nekudotayim,它更自然=) – Rudie 2010-12-20 00:09:00

+0

啊,謝謝。現在,打擾靜態類的一個很好的理由是什麼? – Teson 2010-12-20 00:16:24

0

::也用於一個類/對象內調用其母公司,例如:

parent::__constructor(); 

此外,如果它是從一個對象中調用(因此不是靜態)。

1

考慮一下:

class testClass { 
    var $test = 'test'; 

    function method() { 
     echo $this->test; 
    } 
} 

$test = new testClass(); 

$test->method(); 
testClass::method(); 

的輸出將是這樣的:

test

Fatal error: Using $this when not in object context in ... on line 7

這是因爲::使靜態調用而->被用來調用一個方法或屬性的類一個類的特定實例。

順便說一句,我不相信你能做到$test::method()因爲PHP會給你一個解析錯誤是這樣的:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in ... on line 14

+0

實際上'$ this :: method();'從PHP5.3開始工作。 (與大多數共享託管服務器無關。) – mario 2010-12-20 00:12:29

+0

@mario感謝您的提示。我在ideone.com上試過這個,所以我得到了這個錯誤。 – treeface 2010-12-20 00:15:16