akufen Posted November 16, 2007 Share Posted November 16, 2007 Hi all! I get a 'Fatal error: Cannot access empty property' message when I try to print out the value of the $id field of the returned $someObject. The odd thing is that the $id field is populated when I try to echo the value in the method which returns $someObject! class someClass { public somefunction { $someObject = new SomeObject; while ($stmt->fetch()) { $someObject->$id = $id; } $stmt->close(); echo (someObject->$id); //This works! return $someObject; } } $clazz = new SomeClass; $someObject = $clazz->somefunction(); $echo someObject->$id; //This doesn't work! Thanks in advance! Quote Link to comment Share on other sites More sharing options...
Cep Posted November 16, 2007 Share Posted November 16, 2007 I am not 100% with class/objects but arent you supposed to have echo $someObject->id; not $echo someObject->$id; Quote Link to comment Share on other sites More sharing options...
akufen Posted November 16, 2007 Author Share Posted November 16, 2007 yeah I typed the wrong thing, I am of course using echo($cssTemplate->$id); I also tried echo($cssTemplate->id); but no success Quote Link to comment Share on other sites More sharing options...
akufen Posted November 16, 2007 Author Share Posted November 16, 2007 So this is how you do it... <?php class myCar { var $color = "silver"; var $make = "Mazda"; var $model = "Protege5"; } $car = new myCar(); $car -> color = "red"; $car -> make = "Porsche"; $car -> model = "Boxter"; echo "I drive a: ".$car -> color." ".$car -> make." ".$car -> model; ?> My mistake was that I was using something like $car -> $color = 'some color'; when the correct way to assign a field value to an object is $car -> color 'some color'; (with the $ removed from the field name). Quote Link to comment Share on other sites More sharing options...
obsidian Posted November 16, 2007 Share Posted November 16, 2007 Just to throw some fuel to the fire, $car->$var is actually allowable, too, but it's the value of $var that gets parsed as the variable name. Check this out: <?php class myCar { var $color; var $make; var $model; function myCar($color = '', $make = '', $model = '') { $this->color = $color; $this->make = $make; $this->model = $model; } function getMake() { return $this->make; } } $car = new myCar('silver', 'Mazda', 'Protege 5'); $func = 'getMake'; echo $car->$func(); ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.