使用PDO(php)不在子类中映射SuperClass字段

时间:2014-06-05 17:26:28

标签: php inheritance

我有PersistentObject类,如下所示

abstract class PersistentObject implements IPersistable
{
    private $id;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }
}

和UserModel扩展PersistentObject

class UserModel extends PersistentObject
{
    public static $TABLE_NAME = "user";

    private $email;

    private $username;

    private $password;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }
}

现在我用pdo

获取usermodel
$entity = $stmt->fetchObject("UserModel");

我得到了结果(var_dump($ entity)):

object(UserModel)[11]
  private 'email' => string 'andrewwww@gmail.com' (length=24)
  private 'username' => string 'andrewww' (length=13)
  private 'password' => string '72bed4064dbe53d7fc5fd078214387c813c1f670' (length=40)
  private 'id' (PersistentObject) => null
  public 'id' => string '2' (length=1)

如果我尝试

var_dump($entity->getId());

我收到空;

如何将超类字段映射到子类? 日Thnx!

1 个答案:

答案 0 :(得分:0)

这正是privateprotected之间的区别。

来自http://php.net/manual/en/language.oop5.visibility.php

  

声明受保护的成员只能在类本身以及继承和父类中访问。声明为私有的成员只能由定义成员的类访问。

所以在父类中使用protected

abstract class PersistentObject implements IPersistable
{
    protected $id;
    ...