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! 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 what are you trying to do? do you have a class inside a class? do you know anything about class referencing? extends? 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 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. Link to comment https://forums.phpfreaks.com/topic/271111-class-operators/#findComment-1394861 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.