dongqishun6409
2014-03-03 10:43
浏览 37
已采纳

在PHP代码中访问私有变量

Why doesn't the following output the data I'm expecting?

class student
{
    private $name;
    private $id;

    public function _construct($name,$id)
    {
        $this->name = $name;
        $this->id = $id; 
    }

    public function getName()
    {
        return $this->name;
    }

    public function getID ()
    {
        return $this->id;
    }
}
$mhs = new student("budi","152012102");

echo "name = ".$mhs->getName();

I don't know what's happening, help?

图片转代码服务由CSDN问答提供 功能建议

为什么下面没有输出我期望的数据?

  class student 
 {
 private $ name; 
 private $ id; 
 
 public function _construct($ name,$ id)
 {
 $ this-> name = $ name;  
 $ this-> id = $ id;  
 
 
 
公共函数getName()
 {
返回$ this-> name; 
} 
 
公共函数getID()
 {
返回$ this-> id;  
} 
} 
 $ mhs =新学生(“budi”,“152012102”); 
 
echo“name =”。$ mhs-> getName(); 
   
 
 

我不知道发生了什么事,请帮忙吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duandou1903 2014-03-03 10:44
    最佳回答

    Two problems:

    1) Calling the constructor

    When you call the constructor, you need to prefix it with TWO underscores.

    So in full, you constructor should be:

    public function __construct($name, $id)
    {
        $this->name = $name;
        $this->id = $id;
    }
    

    2) Typo

    There also seems to be a simple typo in your constructor:

    You're assigning $nama instead of $name

    $this->name = $nama;

    This should be

    $this->name = $name;

    [EDIT] This typo seems to be fixed in the main question now

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题