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! Link to comment https://forums.phpfreaks.com/topic/77611-solved-elementary-php-question/ 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; Link to comment https://forums.phpfreaks.com/topic/77611-solved-elementary-php-question/#findComment-392842 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 Link to comment https://forums.phpfreaks.com/topic/77611-solved-elementary-php-question/#findComment-392849 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). Link to comment https://forums.phpfreaks.com/topic/77611-solved-elementary-php-question/#findComment-392854 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(); ?> Link to comment https://forums.phpfreaks.com/topic/77611-solved-elementary-php-question/#findComment-392871 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.