【问题标题】:What is the difference between '::' and '->' with PHP objects? [duplicate]'::' 和 '->' 与 PHP 对象有什么区别? [复制]
【发布时间】:2019-02-09 18:59:53
【问题描述】:

我对对象的不同约定以及访问它们的函数和变量有点困惑。

当我从对象或对象内访问某些内容时,我知道如何使用->。当我在一个可以使用parent::itemclassname::item 的对象中时,我也知道同样的情况,但我不知道除了使用它们之外,因为它们有效。有人会为我分解这些并解释我何时以及为什么应该使用一种方法而不是另一种方法吗?

class mammal{
    public age = 7;
}

class dog extends mammal{
    public dogSpecificVal;

    public function getAge(){
        return $this->age;
        return $parent::age;
        return $mammal::age;
    }
}

$clifford = new dog();
$cliffordAge = $clifford->getAge();

在该示例中,我使用了三种不同的方法来检索年龄。它们都有效,但我不知道为什么或何时应该使用其中一个。

【问题讨论】:

标签: php


【解决方案1】:

在类方法中,可以使用 ->(对象运算符)访问非静态属性:$this->property(其中 property 是属性的名称)。使用 ::(双冒号)访问静态属性:self::$property。有关静态和非静态属性之间区别的更多信息,请参阅静态关键字。

http://php.net/manual/en/language.oop5.properties.php

http://php.net/manual/en/language.oop5.visibility.php

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 2012-12-15
    • 2010-12-17
    相关资源
    最近更新 更多