<?php
class abhi
{
var $contents="default_abhi";
function abhi($contents)
{
$this->$contents = $contents;
}
function get_whats_there()
{
return $this->$contents;
}
}
$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();
?>
i've initialized variable contents a default and also constructor, why is the value not printing, anything i should correct here?
see the error,
abhilash@abhilash:~$ php5 pgm2.php
Fatal erro开发者_高级运维r: Cannot access empty property in /home/abhilash/pgm2.php on line 13
abhilash@abhilash:~$
You are returning the variable incorrectly inside the function. It should be:
return $this->contents
Since the question is tagged as "php5" here's an example of your class with php5 class notation (i.e. public/protected/private instead of var, public/protected/private function, __construct() instead of classname(), ...)
class abhi {
protected $contents="default_abhi";
public function __construct($contents) {
$this->contents = $contents;
}
public function get_whats_there() {
return $this->contents;
}
}
$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();
If i recall correctly it would be
$this->contents = $contents;
not
$this->$contents = $contents;
Should be accessing and writing to $this->contents not $this->$contents
Also, are you not missing a dollar-sign in "echo abhilash->get_whats_there();"? ($abhilash->..)
use $this->contents
i too at first had the same problem
You have a problem with $: 1. when using $this-> you do not put $ between "->" and the variable name the "$" sign, so your $this->$contents should be $this->contents. 2. in your echo youforgot the $ when calling that function from the instantiated class.
So your correct code is:
<?php
class abhi
{
var $contents="default_abhi";
function abhi($contents)
{
$this->contents = $contents;
}
function get_whats_there()
{
return $this->contents;
}
}
$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();
?>
精彩评论