2010-01-15 238 views
1
<?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(); 

?> 

我已经初始化变量内容的默认和构造函数,为什么值不打印,我应该在这里纠正什么?php代码没有执行?

看到错误,

[email protected]:~$ php5 pgm2.php 

Fatal error: Cannot access empty property in /home/abhilash/pgm2.php on line 13 
[email protected]:~$ 

回答

14

您错误地返回该变量的函数中。它应该是:

return $this->contents 
+0

什么Extrakun意味着设置或获取对象的变量时,你不包括$。 – 2010-01-15 14:19:23

+0

作业也是如此。 – falstro 2010-01-15 14:19:46

+2

实际上还存在另一个问题...... echo语句在abhilash变量名称前需要一个美元符号。 – Narcissus 2010-01-15 14:26:50

4

如果我记错这将是

 
$this->contents = $contents; 

 
$this->$contents = $contents; 
3

应该访问和写入被$ this->内容不是$这 - > $内容

0

使用$ this-> contents
我也是第一次有相同的公关Oblem

1

另外,你是否错过了“echo abhilash-> get_whats_there();”的美元符号? ($ abhilash-> ..)

5

由于问题被标记为“PHP ”这里是你的类与php5 class notation一个例子(即公共/保护/私有的,而不是无功,公共/保护/私有函数, __construct()代替类名(),...)

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(); 
+0

+1我正要写相同的...我太慢了。 – 2010-01-15 14:29:36

+0

是否有任何理由重新分配构造函数中的内容?我知道原来的海报有,但是它有价值吗? – Tom 2010-01-15 14:40:22

+0

@Tom:你可以在运行时通过'$ a = new abhi('new content')设置内容' – 2010-01-15 15:08:54

0

你有$一个问题: 1.使用$这个 - 当>你不把$之间 “ - >” 和变量名“$”符号,所以你的$ this - > $内容应该是$ this-> contents。 2.在你的echo中,当从实例化的类中调用该函数时,你可以获得$。

所以,你的正确的代码是:

<?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(); 

?>