【问题标题】:Can't echo newly Assigned value of Class Variable in PHP无法在 PHP 中回显类变量的新分配值
【发布时间】:2014-09-16 14:04:00
【问题描述】:

这是我的代码:

<!DOCTYPE html>
<html>
    <head>
      <title>Reconstructing the Person Class</title>
      <link type='text/css' rel='stylesheet' href='style.css'/>
    </head>
    <body>
      <p>
        <?php 
            class Person {
                public $isAlive = true;
                public $firstname;
                public $lastname;
                public $age;

                public function __construct() {
                    $this->firstname = "Umair";
                    $this->lastname = "Dongle";
                    $this->age = 23;
                }
            }
            $teacher = new Person("Matt","Zinger",34);
            $student = new Person("Hassan", "Naseer", 90);
            echo $teacher->age;
        ?>
      </p>
    </body>
</html>

这个结果应该是 34,但我得到了 23。有人可以解释一下,因为我是 PHP 新手,还在学习。如果 -> 这个有线的东西有另一种语法,那么也请告诉我。 谢谢

【问题讨论】:

  • 你的构造器上没有参数
  • 每次构建新对象时,您都会为变量分配相同的硬编码值。

标签: php class oop constructor


【解决方案1】:

你必须为你的构造函数提供参数:

public function __construct($_f, $_l, $_a) {
    $this->firstname = $_f;
    $this->lastname = $_a;
    $this->age = $_a;
}

更多内容请关注documentation

【讨论】:

    【解决方案2】:

    正如Ghost 提到的,您的构造函数__construct() 中没有任何参数。因此 PHP 放弃了参数以支持在构造函数中指定的硬编码值。

    以下应该有效:

    public function __construct($firstname, $lastname, $age) {
        $this->firstname = $firstname;
        $this->lastname = $lastname;
        $this->age = $age;
    }
    

    没有替代语法可以访问类的成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 2017-05-06
      相关资源
      最近更新 更多