TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   How to access the method of an object that is inside an object (http://www.talkphp.com/advanced-php-programming/3600-how-access-method-object-inside-object.html)

tony 11-13-2008 02:04 AM

How to access the method of an object that is inside an object
 
Hi guys and gals, once again i hit bump in this project.
the thing is that I have 2 classes, well I think it's better if i put the code first:

PHP Code:

<?php
class foo{
    private 
$a;
    private 
$b;
    
    function 
__construct(){
        
$this->a=3;
        
$this->b=3;
    }
    
    public function 
getA(){    return $this->a; }
    public function 
getB(){    return $this->b; }
    public function 
setA($t){ $this->a=$t; }
    public function 
setB($t){ $this->a=$t; }
}

clas bar{
    
$private c;
    
$private d;
    
    function 
__construct(){
        
$this->c=10;
        
$this->d= new foo;
    }
    
    public function 
getC(){ return $this->}
    public function 
getD(){ return $this->}
    public function 
setC($t){ $this->c=$t; }
    public function 
setD($t){ $this->d=$t; }
}
?>

now the problem rises when i want to get the getA() method from an instance of bar, like this:

PHP Code:

<?php
$house
=new Bar;
echo 
$house->getD()->getA(); // it should output 3 ideally 
?>

but I get this "Fatal error: Can't use method return value in write context"

any ideas on what i am doing wrong? thanks for the help in advance.

Wildhoney 11-13-2008 02:13 AM

1 Attachment(s)
That returns 3 for me. Are you trying to do something like the following, because this is really the only way I can think of causing that error you're getting:

php Code:
if (empty($house->getD()->getA()))
{
   
}

tony 11-13-2008 02:20 AM

yes! i am trying to see if they are empty, I forgot to mention that.

Wildhoney 11-13-2008 02:26 AM

I see, I see! Sadly, empty cannot check the return value, for some unknown reason. I don't know the real reasoning behind it. Assign the value to a variable first, and then check if that variable is empty or not.

php Code:
$iValue = $pHouse->getD()->getA();

if (empty($iValue))
{

}

tony 11-13-2008 02:43 AM

Awesome, that worked! though I am curious as to why. I'll search more after I finish the project.
Thanks for the help :)

Wildhoney 11-13-2008 02:46 AM

And please let us know, too! Best of luck, my friend :-)


All times are GMT. The time now is 02:41 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0