[英]Can't echo newly Assigned value of Class Variable in PHP
這是我的代碼:
<!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。 並且如果還有->這種有線方式的替代語法,請也告訴我。 謝謝
如Ghost所述,構造函數__construct()
沒有任何參數。 因此,PHP放棄了參數,而贊成在構造函數內部指定的硬編碼值。
以下應該工作:
public function __construct($firstname, $lastname, $age) {
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->age = $age;
}
沒有其他語法可以訪問類的成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.