'Laravel: Why is my variable not being set while it's in the construct function of the controller?
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
private $host;
private function __construct()
{
$environment = App::environment();
if ($environment == "local"){
$this->host = config('customs.localHost');
}
else if ($environment == "prod"){
$this->host = config('customs.productionHost');
}
}
public function getHost()
{
return $this->host;
}
}
Above is my controller in the Laravel. This is the main controller, I extend this controller in my other controller classes. Basically I wanted to create a method in this controller which returns the current host according to my current environment.
I'm calling the function getHost() from my other controllers, however I'm getting null.
Now the code in the __construct(), if I put it in the getHost() method it works. However my question here is why doesn't the code in the __construct() get executed?
Solution 1:[1]
you must call
parent::__construct();
inside the subclass constructor, and the superclass constructor must not be private.
E.g.:
public function __construct() {
parent::__construct();
// do something
}
Solution 2:[2]
I thought when I'm extending the controller it automatically initializes.
class WSUsersController extends Controller
{
}
I had to initialize my controller before calling the getHost() method.
$controller = New Controller();
$result['campaignRequest'] = $controller->getHost();
Solution 3:[3]
Change visibility of property $host:
public $host;
and visibility of function __construct:
public function __construct()
then in your subclass construct function:
parent::__construct();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Samuel Liew |
Solution 2 | Pops |
Solution 3 |