PHP依赖注入子类

时间:2014-01-03 11:24:17

标签: php dependency-injection parent-child

假设我有以下php类:class user,class fileManager和class downloader extends fileManager

<?php
class user {
  private $name;
  public function __construct($name){
     $this->_name = $name;
  }
  public function getName(){
     return $this->_name;
  }
}
class fileManager {
  protected $user, $list;
  public function __construct($user, $list){
    $this->_user = $user;
    /* IF list is 1 OR 2... */
    $this->_list = $list
    /* for test: */
    echo $this->user->getName(); /* WORKS */
  }
  /* SOME METHODS */
}
class downloader extends fileManager {

  public function download($fileid){
    $this->_fileid = $fileid;
    /* if his username is set, he is logged in */
    if($this->user->getName()!=null){continue();}
  }
}

$user = new user('Jan');
echo $user->getName(); /* = jan */
$fm = new fileManager($user, 1);
$down = new downloader();
$down->download(1); 
/* FATAL ERROR, Call to a member function getName() on a non-object */
?>

所以,jan已登录,并打开文件管理器。 filemanager从用户类调用getName并知道它是jan。但是如果Jan想要下载文件1,那么下载器就不会识别Jan.为什么?是不是应该从父类继承属性的子类?

2 个答案:

答案 0 :(得分:1)

$ down是一个新对象。 - &GT;构造函数需要params。 试试

$user = new user('Jan');
echo $user->getName(); /* = jan */
$fm = new fileManager($user, 1);
$down = new downloader($user, 1);
$down->download(1);

答案 1 :(得分:0)

不考虑拼写错误,您必须在实例化下载类时将值传递给构造函数。

class user {
  private $name;
  public function __construct($name){
     $this->_name = $name;
  }
  public function getName(){
     return $this->_name;
  }
}
class fileManager {
  protected $user, $list;
  public function __construct($user, $list){
    $this->_user = $user;
    /* IF list is 1 OR 2... */
    $this->_list = $list;
    /* for test: */
    echo $this->_user->getName(); /* WORKS */
  }
  /* SOME METHODS */
}
class downloader extends fileManager {


  public function download($fileid){
    $this->_fileid = $fileid;
    /* if his username is set, he is logged in */
    if($this->_user->getName()==null)
        return false;

    //download file

  }
}

$user = new user('Jan');
echo $user->getName(); /* = jan */
$fm = new fileManager($user, 1);
$down = new downloader($user, 1);
$down->download(1);