开发者

Where do we use the object operator "->" in PHP?

开发者 https://www.devze.com 2023-01-03 14:57 出处:网络
What are the different ways where we 开发者_开发知识库can use object operators -> in PHP?PHP has two object operators.

What are the different ways where we 开发者_开发知识库can use object operators -> in PHP?


PHP has two object operators.

The first, ->, is used when you want to call a method on an instance or access an instance property.

The second, ::, is used when you want to call a static method, access a static variable, or call a parent class's version of a method within a child class.


When accessing a method or a property of an instantiated class

class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}

$a = new SimpleClass();
echo $a->var;
$a->displayVar();


Call a function:

$foo->bar();

Access a property:

$foo->bar = 'baz';

where $foo is an instantiated object.


It is used when referring to the attributes of an instantiated object. e.g:

class a {
    public $yourVariable = 'Hello world!';
    public function returnString() {
        return $this->yourVariable;
    }
}

$object = new a();
echo $object->returnString();
exit();


"->" operator is the PHP related callable content. always use to call an instance method and access instance.

"::" scope operator is used for the instance that is used for calling the static method and constant it's very different with::

It's a proper reply to them, I have got new knowledge.

Please check the name conflicts for the above different operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消