Can't access empty property?
I am trying to get into php object oriented programming.
<?php
class myClass{
public $myVar="this is demo";
public function myTextdemo(){
echo $myVar;
}
}
$obj= new myClass;
echo $obj->$myVar;
?>
It says
Fatal error: Cannot access empty property on line 11
What's wrong with my code?
arunpawar
Junior Poster in Training
66 posts since Dec 2007
Reputation Points: 9
Solved Threads: 0
Skill Endorsements: 0
Change it like this:
<?php
class myClass
{
public $myVar="this is demo";
public function myTextdemo()
{
return $this->myVar; # the problem was here
}
}
$obj = new myClass();
echo $obj->myVar; # and here you wrote $obj->$myVar with an extra $
?>
use return to output data from a function not echo and use $this inside the class functions, otherwise the declared property will not be considered and you will get an error like Undefined variable...
http://www.php.net/manual/en/language.oop5.properties.php
bye! :)
cereal
Veteran Poster
1,144 posts since Aug 2007
Reputation Points: 344
Solved Threads: 222
Skill Endorsements: 22
Awesome. Solved. THanks cereal :)
arunpawar
Junior Poster in Training
66 posts since Dec 2007
Reputation Points: 9
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 9 Months Ago by
cereal