Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP double arrow notation for instances of an class(es)

Tags:

oop

php

I would be grateful if someone explained to me the use of double arrow notation in PHP. I suggest is a double classes and instantiation of that classes, but I am not sure. Some examples will be good. Thanks.

Something like this:

$obj->prop->methd();
like image 915
Dexy_Wolf Avatar asked Jul 24 '11 12:07

Dexy_Wolf


Video Answer


2 Answers

This just indicates that $obj has a property that is a class of some kind rather than an atomic variable. The inner class has a method method() which is called from the second arrow operator. You could also access properties of the inner class via the second arrow.

// Access the inner property
echo $obj->prop->inner_property
// 1234

// Call the inner method
$obj->prop->method();
// I'm the method!

The class definitions might be something like:

class obj
{
   // Will hold an instance of class Something
   public $prop;

   public function __construct() {
      $this->prop = new Something();
   }
}

class Something 
{
   public $inner_property = 1234;

   public function method() {
     echo "I'm the method!";
   }
}
like image 151
Michael Berkowski Avatar answered Nov 02 '22 23:11

Michael Berkowski


As an example, take for instance two classes:

<?php

class a {
    function test() {
        echo "test";
    }
}

class b {
    var $prop = null;
    function __construct() {
        $this->prop = new a();
    }
}

$obj = new b();
var_dump($obj);
$obj->prop->test();

?>

http://codepad.org/aEeRs45A

Class a gives $prop a method when b is instantiated and the constructor is called. $prop in b is an object of class b.

like image 26
Jared Farrish Avatar answered Nov 02 '22 23:11

Jared Farrish