Page 1 of 1

Objects and passthrough values - odd behaviour?

Posted: Wed Mar 26, 2008 3:59 pm
by Popepalpatine
Hi, I'm learning php and am trying to figure out how the OO portion works. I'm quite familiar with JAVA and so none of the concepts are that new, only the implementation.

I'm trying to understand why this gives me an error:
- Note I know from a design point of view it doesn't really make sense to have the tag modifiable both through the Dog and directly, but I'm just trying to get an understanding of how the method calls and pathroughs work.

Here's most of the code, the error it gives is "Call to a member function setLabel() on a non-object":

<--

// This just defines a DogTag. No Problem here - I think!
class DogTag{
private $Label;

public function __construct(){
$Label = "not set";
}

public function setLabel($newLabel){
$this->Label = $newLabel;
}

public function getLabel(){
return $this->Label;
}
}

//Here's the Dog Class where the problem is
class Dog{
private $tag;

public function __construct(){
$tag = new DogTag();
}

public function getDogLabel(){
return $this->tag->getLabel();
}

//The error is in this function
public function setDogLabel($newLabel){
$this->tag->setLabel($newLabel);
}

}

$Zoe = new Dog();
$Zoe->setDogLabel("Yo my name is Zoe Dog.\n");
echo $Zoe->getDogLabel();

-->

But if I replace:

public function setDogLabel($newLabel){
$this->tag->setLabel($newLabel);
}

with

public function setDogLabel($newLabel){
$tempTag = new DogTag();
$tempTag->setLabel($newLabel);
$this->tag = $tempTag;
}

Then there's no problem! This approaches seems clumsy. I don't understand what's going on here. Why can I define getDogLabel() as return $this->tag->getLabel(); but not setDogLabel in the same way??

Thanks so much for the help! BTW I'm using PHP 5.2.5

Paul

Re: Objects and passthrough values - odd behaviour?

Posted: Wed Mar 26, 2008 4:28 pm
by Christopher
The constructors in the examples above are wrong. They should be:

Code: Select all

public function __construct(){
$this->Label = "not set";
}
 
public function __construct(){
$this->tag = new DogTag();
}
 
One person's clumsy or is another person's consistent. ;) In PHP you always use $this->, self:: or parent:: to access properties. You always access local variables as $name. In Java and other languages you can access properties via their short name if there is no naming conflict with a local variable.

Re: Objects and passthrough values - odd behaviour?

Posted: Wed Mar 26, 2008 5:01 pm
by Popepalpatine
Ahhhh that makes sense - and is consistent. :D

Thanks!