我对 PHP 还很陌生,我正在尝试了解工作类、方法和属性。我有一个问题,我想得到解决,但我没有得到。我找不到合适的解决方案(我也很喜欢)。
在我问我的问题之前,这里是我的课程/代码:
主类用户(user.class.php)
class User {
// Properties
protected $_name;
public $surname;
// Methods
public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function setSurname($surname) {
$this->surname = $surname;
}
public function getSurname() {
return $this->surname;
}
}
子类 *Premium_User* (premiumUser_child_user.class.php)
class Premium_User extends User {
private $_premiumId;
public function setData($name, $id) {
$this->name = $name;
$this->_premiumId = $id;
}
public function getData() {
return array(
'name' => $this->name,
'id' => $this->_premiumId
);
}
}
编码:
// Class User::
include('user.class.php');
// Child class -> class::User
include('premiumUser_child_user.class.php');
$user = new Premium_User();
$user->setData('P','1');
$user->setData('H','2');
$user->setData('P','3');
$getUserData = $user->getData();
while ($i <= $getUserData['id'] ) {
echo "User: " . $getUserData['name'] . " ID: " . $getUserData['id'] . ".\n"; <br>
$i++;
}
输出:
User: P ID: 3.
User: P ID: 3.
User: P ID: 3.
我想得到的是:
User: P ID: 1.
User: H ID: 2.
User: P ID: 3.
我尝试使用 *array_push* 将每个条目添加到数组中,但没有奏效。