【问题标题】:oophp, method and property namingoophp、方法和属性命名
【发布时间】:2011-05-28 00:26:56
【问题描述】:

在php中,使用有什么区别

$myClass::method()

$myClass->method()

改变的原因是什么? (我相信-> 的存在时间更长。)

我可以看到将:: 用于方法,将-> 用于属性,反之亦然。

【问题讨论】:

标签: php oop naming-conventions


【解决方案1】:

:: 是作用域解析运算符,用于访问类的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();

【讨论】:

  • PHP 称它为 Paamayim Nekudotayim,这更加自然 =)
  • 啊,谢谢。现在,有一个很好的理由来打扰静态类吗?
  • @user247245:static 关键字仅对类变量是必需的。对于方法,您可以跳过staticpublic,因为它们对语义的改变很小。静态类本身对分组方法很有意义(= 可怜的 mans 命名空间)。
【解决方案2】:

:: 也用于类/对象中以调用其父级,例如:

parent::__constructor();

如果它是从一个对象中调用的(所以不是静态的)。

【讨论】:

    【解决方案3】:

    考虑一下:

    class testClass {
        var $test = 'test';
        
        function method() {
            echo $this->test;
        }
    }
    
    $test = new testClass();
    
    $test->method();
    testClass::method();
    

    输出将类似于:

    测试

    致命错误:在第 7 行的...中不在对象上下文中使用 $this

    这是因为:: 对类进行静态调用,而-> 用于调用类的特定实例的方法或属性。

    顺便说一句,我不相信你能做到$test::method(),因为 PHP 会给你一个像这样的解析错误:

    解析错误:语法错误,第 14 行中的意外 T_PAAMAYIM_NEKUDOTAYIM ...

    【讨论】:

    • 实际上$this::method(); 从 PHP5.3 开始工作。 (与大多数共享托管服务器无关。)
    • @mario 感谢您的提示。我在 ideone.com 上试过这个,这就是我得到错误的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多