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
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. :)

Edited by Andy123
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.