1

I am fairly new in PHP and want to ask a question. I know if you want to access a properties or method within a class or object you can use $this->properties or $this->method.

But I encountered a code like this $this->context->cart

Can someone please explain the meaning behind this code ?

If there is another similar question already being asked in SO can you please provide me the link, I will check it out.

Big Thanks

Thomas Rollet
  • 1,573
  • 4
  • 19
  • 33
myd07
  • 93
  • 3
  • 11
  • Context is probably a property of this class that is an instance of another class. – Jerodev Mar 09 '17 at 08:15
  • 1
    Possible duplicate of [Reference - What does this symbol mean in PHP?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – LF00 Mar 09 '17 at 08:17
  • It is a nested property or method. It'll mainly come up in object oriented code where an object contains another object as a property which itself has properties and or methods. – M31 Mar 09 '17 at 08:17
  • In case of a property, the property contains an object that has properties and methods itself. In case of a method, the method returns an object, either itself - so that you can chain methods - or another object. – jeroen Mar 09 '17 at 08:18
  • And one correction to your own statement for the sake of precision: `$this`does _not_ allow access to properties or methods of a _class_ but _only_ of an object. – arkascha Mar 09 '17 at 08:19
  • Hi guys, so cart is a properties from context class ? is my understanding correct ? – myd07 Mar 09 '17 at 08:53
  • @myd07 yes. it's correct. see [this](http://stackoverflow.com/a/42699561/2302051) – MahdiY Mar 10 '17 at 13:04

2 Answers2

4

See and try it:

class class1 {

    public $properties;
    public $context;

    function __construct(){

        $this->properties = '$properties in class1';
        $this->context = new class2(); // instance of class2

    }
}

class class2 {

    public $cart;

    function __construct(){

        $this->cart = '$cart in class2';

    }

}

$obj = new class1();

echo $obj->properties;
echo $obj->context->cart;
MahdiY
  • 1,269
  • 21
  • 32
0

context is instance of another class for retrive method or property of that class this is use