nectar
nectar

Reputation: 9679

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

What are the different ways where we can use object operators -> in PHP?

Upvotes: 99

Views: 106267

Answers (6)

Bilal Ahmad
Bilal Ahmad

Reputation: 1

arrow operator(->): It is an access operator used to access data members and methods in a class in PHP. It is the same as the (.) operator which we use in javascript, c++.

Upvotes: -1

李沣泉
李沣泉

Reputation: 11

"->" 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.

Upvotes: 1

Wind Chimez
Wind Chimez

Reputation: 1176

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();

Upvotes: 4

Powerlord
Powerlord

Reputation: 88796

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.

Upvotes: 138

mmattax
mmattax

Reputation: 27670

Call a function:

$foo->bar();

Access a property:

$foo->bar = 'baz';

where $foo is an instantiated object.

Upvotes: 11

Mark Baker
Mark Baker

Reputation: 212412

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();

Upvotes: 31

Related Questions