user3156884
user3156884

Reputation: 3

PHP dependency injection child class

let's say I have the following php classes: class user, class fileManager and 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 */
?>

So, jan is logged in, and opens the filemanager. The filemanager calls getName from the user class and knows thats it's jan. But if Jan wants to download file 1, the downloader doesn't recognize Jan. Why ? Aren't child classes supposed to inherit properties from parent classes?

Upvotes: 0

Views: 187

Answers (2)

Stefano Esse
Stefano Esse

Reputation: 1

Not considering the typos, you have to pass values to the constructor when you instantiate the download class.

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

Upvotes: 0

niyou
niyou

Reputation: 873

$down is a new object. -> The constructor needs params. Try

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

Upvotes: 1

Related Questions