【问题标题】:Defining class attribute with scope from method使用方法范围定义类属性
【发布时间】:2017-10-13 09:22:15
【问题描述】:

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

当前代码

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;
    }
}

结果(打印_r)

UserEntity Object

( [数据库:受保护] => 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

)

谢谢!

【问题讨论】:

  • 抱歉结果有问题。

标签: php class


【解决方案1】:

您需要提前声明属性:

class UserEntity extends Entity {

    private $wachtwoord;
    public $firstname;

    ...
}

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

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 2013-06-27
    • 2014-06-18
    • 2012-04-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多