0

我对 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* 将每个条目添加到数组中,但没有奏效。

4

2 回答 2

2

您只创建一个用户而不是三个独立的用户。如果您想拥有三个用户,请使用3 次创建三个。new

setData()您在同一个对象上调用三次。

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

通过此定义,您将覆盖对方法的先前调用的更改setData。我已经评论了对你没有影响的行:

$user = new Premium_User();
// $user->setData('P','1');
// $user->setData('H','2');
$user->setData('P','3');

要通过单个变量访问多个用户,您可以将用户放入数组中:

$user1 = new Premium_User();
$user1->setData('P','1');
$user2 = new Premium_User();
$user2->setData('H','2');
$user3 = new Premium_User();
$user3->setData('P','3');

用于 PHP 5.4 及更高版本:

$users = [$user1, $user2, $user3];
foreach($users as $user) {
    echo "User: " . $user->getData()['name'] . " ID: " . $user->getData()['id'] . ".\n";
}

PHP 5.4 之前:

$users = array($user1, $user2, $user3);
foreach($users as $user) {
    $userData = $user->getData(); 
    echo "User: " . $userData['name'] . " ID: " . $userData['id'] . ".\n";
}
于 2013-05-06T20:21:48.643 回答
0

该类只记住您上次设置数据的时间。要么实例化多个用户,要么一次设置一个用户,一次输出一个。

$user = new Premium_User();
$user->setData('P','1'); 

$user2 = new Premium_User();
$user2->setData('H','2'); 

$user3 = new Premium_User();
$user3->setData('P','3'); 

仅供参考,在<br>您使用回声之前不需要标签。

或使用:

$user = new Premium_User();
$user->setData('P','1');
//do something with this user data
$user->setData('H','2'); 
//do something with second user data
//etc.
于 2013-05-06T20:22:38.700 回答