I have a Laravel controller with a protected var that I want to use in many other controllers, however when I try to access it in child class I got the error:
Call to a member function add() on null
which means that the previously initiated variable is now null and I don’t know why, the code:
class Controller extends BaseController {
protected $ipfs_node_root;
public function __construct()
{
Funcoes::consolelog('Controller::creating ipfs node access point...');
$ipfs_node_root = new IPFS();
}
}
in a extended class:
class PostController extends Controller {
private function handle(){
Funcoes::consolelog('PostController::handle uploading file content to ipfs node.');
// for the sake of test, I change the _root to _local ipfs_node and it works
$ipfs_node_local = new IPFS();
$arq_hash = $this->ipfs_node_root->add($arq->get());
}
}
The PostController
class has no __construct.
EDIT
I’ve added a __construct method to the child class but the error continues:
public function __construct()
{
parent::__construct();
Funcoes::consolelog('PostController::__construct');
}
2
Answers
When you extend a class containing a constructor, the extension class must also contain a constructor and that constructor must call
parent::_construct()
, or you get what you’re gettting.$ipfs_node_root = new IPFS();
is setting a separate, locally scoped variable that doesn’t exist outside the constructor.You want
$this->ipfs_node_root = new IPFS();
instead.