Reputation: 177
Perhaps my question is vague, so let me make it clear. I've created a controller file, say, SomeController.php
and here in my LoginController
I have:
use SomeController;
private $instance;
public function someRouteDefinedInRouteFile() {
$this->instance = new SomeController; // now $this->instance must have SomeController instance
return $this->instance;
}
public function someOtherRoute() {
return $this->instance; // it must return the instance but it's null
}
If someRouteDefinedInRouteFile()
is called $this->instance
must have the instance of SomeController
. But after calling someAnotherRoute()
, $this->instance
is null
Upvotes: 2
Views: 338
Reputation: 1062
If you want use a instance in all methods it must be set in constructor or create setter method and call this method in each method that want use instance.
Examples:
1:
`public function someRouteDefinedInRouteFile(SomeController $instance) {
$this->instance = $instance; // now $this->instance must have SomeController instance
return $this->instance;
}
2:
function getInstanceSomeController(){
return new SomeController;
}
But i don't understand why you need to other controller instance? maybe you will can use library or general class.
Upvotes: 1
Reputation: 163788
This is because these methods are executed during separate requests. If you want to use the same instance, use IoC to inject the class in controller constructor.
protected $istance;
public function __construct(Instance $instance)
{
$this->instance = $instance;
}
Then you'll be able to use it in any controller's methods.
Upvotes: 2