2010-12-19 60 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