使用方法的范围定义class属性

时间:2017-10-13 09:22:15

标签: php class

我尝试使用方法在类中创建属性。可以创建属性,但如何向属性添加范围?例如,我希望wachtwoord(密码)是私有的,但是名字是公开的。

当前代码

class UserEntity extends Entity{

/**
 * UserEntities constructor.
 */
public function __construct($user_id){
    parent::__construct();
    $this->loadDatabase();
    $this->get($user_id);
}

/**
 *  Get user form database
 *
 *  @param $user_id
 */
private function get($user_id){

    $prepare = $this->database->prepare("
        select * from gebruiker where gebruikerid = :user_id;
    ");

    $prepare->bindValue(':user_id', $user_id);
    $prepare->execute();
    $result =  $prepare->fetch($this->fetchMethod);

    foreach($result as $key => $value){
        $this->{$key} = $value;
    }
}

结果(Print_r)

UserEntity Object

(     [database:protected] => PDO对象         (         )

[gebruikerid] => test_val
[0] => test_val
[voornaam] => test_val
[1] => test_val
[achternaam] => test_val
[2] => test_val
[email] => test_val
[3] => test_val
[rol] => test_val
[4] => test_val
[wachtwoord] => test_val
[5] => test_val
[laatstelogin] => test_val
[6] => test_val
[status] => test_val
[7] => test_val
[registratiedatum] => test_val
[8] => test_val
[afbeeldingurl] => test_val
[9] => test_val
[initialen] => test_val
[10] => test_val
[geboortedatum] => test_val
[11] => test_val
[bsn] => test_val
[12] => test_val
[laatstonline] => test_val
[13] => test_val

谢谢!

1 个答案:

答案 0 :(得分:2)

您需要提前声明属性:

class UserEntity extends Entity {

    private $wachtwoord;
    public $firstname;

    ...
}

动态添加的属性始终是公开的。