drbz99867 2014-06-05 09:26
浏览 54
已采纳

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

I have the PersistentObject class as following

abstract class PersistentObject implements IPersistable
{
    private $id;

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

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

and the UserModel extending the 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;
    }
}

now when I fetch the usermodel with pdo

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

I'm getting the result ( 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)

and if I try

var_dump($entity->getId());

I receive null;

How is it possible to map the superclass fields into the subclass??? thnx!

展开全部

  • 写回答

1条回答 默认 最新

  • dovgqc2648 2014-06-14 05:21
    关注

    That's exactly the difference between private and protected.

    From http://php.net/manual/en/language.oop5.visibility.php:

    Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

    So use protected in the parent class:

    abstract class PersistentObject implements IPersistable
    {
        protected $id;
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部