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

在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?

  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错