Page 1 of 1

Howto $obj->getFieldObj()->getField() ?

Posted: Tue Jan 27, 2004 9:18 pm
by seine
Hello PHP guns,

I have a long unanswered question regarding PHP. It's long unanswered because I can easily get around it, but it means writing two lines of code instead of one.

How can I reference a field of a field of an object in one statement? Eg. How can I turn this:

Code: Select all

$aField = $obj->field();
$aResult = $aField->result();
into something like this:

Code: Select all

$aResult = $obj->field()->result();
I hope someone can help!

Thanks heaps
Jem

Posted: Tue Jan 27, 2004 9:57 pm
by McGruff
You can't do that. If you chain objects, they must BE objects ie:

Code: Select all

<?php
$var = $object1->$object2->method();
?>

Posted: Tue Jan 27, 2004 10:34 pm
by seine
Thanks McGruff

As a Java developer I considered accessing fields directly to be an awful violation of encapsulation. But, if that's how it's done in PHP then that's how it's done! Who am I to argue?

Now I have another question, but I'll put it in a new thread, as per the forum guidelines. :)

Thanks again!
Jem

Posted: Wed Jan 28, 2004 9:31 am
by McGruff
seine wrote:Thanks McGruff

As a Java developer I considered accessing fields directly to be an awful violation of encapsulation.
Jem
Php doesn't stop you doing bad programming - which maybe helps the learning curve - but it also doesn't stop you doing good programming.

I agree it's important to clearly define an object interface but you can still do that with a bunch of getters and setters, comments, naming conventions etc.

Personally I think the freedom we have in php is one of its best features.

Posted: Sun Feb 01, 2004 4:22 am
by seine
I'm sorry to admit I still have a bit of confusion over this. Mind if I come back to it?

Given A:

Code: Select all

class Obj01{
    var $anObj02;

    function getObject02() {
        return $this->anObj02;
    }
}
B:

Code: Select all

$anObj01->anObj02;
and C:

Code: Select all

$anObj01->getObject02();
If B returns a reference to an Object02 instance, what does C return? C obviously can't return a reference to an Object02 instance otherwise

Code: Select all

$anObject01Instance->getObject02()->doMethodOnObject02();
would work.

Can anyone enlighten me please? :)

Thanks for keeping up the good work
Jem.


?>[/b]

Posted: Sun Feb 01, 2004 4:28 am
by markl999
Not being able to chain objects like,
$anObject01Instance->getObject02()->doMethodOnObject02();
is just a limitation of PHP4, you can do it in PHP5 :o

Posted: Sun Feb 01, 2004 5:03 am
by seine
Roger that! Thanks a bunch.