Reputation: 2194
I know how to call a function based off a variable like this:
$platform->ConfigurePlatform($client);
Where $platform
is a variable which contains the name of the class.
I am trying to call a function like this, but object based from within the same class. The below will work fine, which is fine for within the same method.
$platform = new $platform_name();
$platform->ConfigurePlatform($client);
But I want to call another method within the object like this:
$this->$platform->GetOrdersFromPlatform();
This will give the error below:
Fatal error: Cannot access empty property (On the line above)
I thought maybe I should create the object like this instead:
$this->$platform = new $platform_name();
However this gives the error below:
Fatal error: Cannot access empty property (On the line above)
How can I achieve this?
Upvotes: 2
Views: 60
Reputation: 1535
If you plan to use the same object in different places of the class, you just need to set it into an attribute of the same class.
class Station
{
public $platform = null;
public function start()
{
$this->platform = new Platform();
$this->platform->ConfigurePlatform('test');
}
public function getOrders()
{
return $this->platform->GetOrdersFromPlatform();
}
}
class Platform
{
private $orders = null;
public function ConfigurePlatform($string)
{
$this->orders = $string;
return $this;
}
public function GetOrdersFromPlatform()
{
return $this->orders;
}
}
$test = new Station();
$test->start();
echo $test->platform->GetOrdersFromPlatform();
//or
echo $test->getOrders();
This is the code tested: https://3v4l.org/UuTgb
Upvotes: 0
Reputation: 2905
Your question is not clear, but I think what you want is method chaining, this can be done by return the $this
property of the class. Example:
class ClassName
{
function ConfigurePlatform($client)
{
// What to do
echo __METHOD__.": ".$client."\n";
// return the $this property to make the class properties chainable
return $this;
}
function GetOrdersFromPlatform($client)
{
// What to do
echo __METHOD__.": ".$client."\n";
// return the $this property to make the class properties chainable
return $this;
}
}
$classObj = new ClassName();
$client = "Firefox/Chrome/Safari";
// Call both methods
$classObj->ConfigurePlatform($client)->GetOrdersFromPlatform($client);
//ClassName::ConfigurePlatform: Firefox/Chrome/Safari ClassName::GetOrdersFromPlatform: Firrefox/Chrome/Safari
Upvotes: 2