Page 1 of 1

OOP Question about referencing objects from objects

Posted: Fri Dec 16, 2005 6:56 pm
by twrofpwr
Hey Guys I have a quick question I have an object that contains another object and I am having difficulties referencing the function from the 2nd object.. I thought this code would work


$number = $this->object_one->method_inside_object_one()->method();


now method_inside_object_one() is a method in object_one, that reutrns an Object, that object has a method "method()"

What do I do?

It seems I hd to break it down like this, in order to get it to work

$temp = $this->object_one->method_inside_object_one();
$temp = $temp->method();

Any suggestions would be greatly appreciated, thanks

Jeff.

Posted: Fri Dec 16, 2005 7:07 pm
by feyd
This isn't a general discussion question... :?

From what I remember, simply using parens around the first part that returns the object you actually want to interact with is the solution.

Posted: Fri Dec 16, 2005 7:42 pm
by BDKR
That has got to be the most convoluted thing i've ever heared. And I'm still not 100% sure I understood it. LOL!!!

In a case where the logic gets so convoluted, you really need to sit down and consider refactoring.

Anyway, may the below will work.

Code: Select all

$number=($this->object_one->method_inside_object_one())->method();
Of course, we know that things inside parenthesis should execute first. In this case, the idea is that your object will be returned and the method run giving back your "number" in the end.

Sorry I can't test this right now as I'm on my Win Boxen getting ready to do some gaming. :twisted:

Cheers,

BDKR

Posted: Fri Dec 16, 2005 9:20 pm
by timvw
If i'm not mistaken php5 supports chaining and php4 doesn't..

Posted: Sat Dec 17, 2005 12:03 am
by twrofpwr
I tried the parenthesis and it didn't work for some reason :S

Maybe only in php 5 that works? I just find it odd that you can't get reference to an object, then access methods within that object all on one line. i have never really explored objects much though with php mainly with java and c++, but now I am really starting to code everything as oop with php, I keep running into problems though :( It doesn't seme to be true oop, although I guess php 5 fixes a lot of this.

Posted: Sat Dec 17, 2005 3:44 am
by Maugrim_The_Reaper
You can't chain in PHP4 - so the above q is only applicable when using PHP5.

Otherwise remember the KISS (Keep It Simple Stupid) rule and consider using a more readable format. Convoluted one-liners are a pain in the ass to figure out. ;) Use up three lines if it works...