Buchead Posted November 24, 2012 Share Posted November 24, 2012 I'm sure most will laugh at this but I'm new to php classes and been some code to alter that has me a little confused. I understand that to call a class function you use $object->function(). However the code I have has $object1->$object2->function(). Does this mean that within $object1 it has objects created that are written to one of it's variables? Sorry again for the stupid question, and thanks! Quote Link to comment https://forums.phpfreaks.com/topic/271111-class-operators/ Share on other sites More sharing options...
50r Posted November 24, 2012 Share Posted November 24, 2012 (edited) what are you trying to do? do you have a class inside a class? do you know anything about class referencing? extends? Edited November 24, 2012 by 50r Quote Link to comment https://forums.phpfreaks.com/topic/271111-class-operators/#findComment-1394773 Share on other sites More sharing options...
Andy123 Posted November 24, 2012 Share Posted November 24, 2012 (edited) The following code: $product->category->getName(); is accessing a public property (I would discourage this protection level, but that's another story) on the Product class and then calling the getName() method on it. So, it first accesses the Product class. Then the category property, which it then calls getName() on. So getName() is called on whichever class category is (probably Category). To illustrate this, consider the implementation below: class Category { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } class Product { public $category; // Use private or protected instead public function __construct(Category $category) { $this->category = $category; } } $category = new Category('my_category'); $product = new Product($category); echo $product->category->getName(); // Prints "my_category" Hope it helps - otherwise feel free to ask further questions. Edited November 24, 2012 by Andy123 Quote Link to comment https://forums.phpfreaks.com/topic/271111-class-operators/#findComment-1394861 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.