Jump to content

Class Operators


Buchead

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.