In PHP you can call a class's static method from an object instance (which is contained in an array) like this:
$myArray['instanceOfMyClass']::staticMethod(); // works
But for some reason when I use the $this
variable, I get a parsing error. E.g:
$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
Just to illustrate what I mean:
class MyClass{
public static function staticMethod(){ echo "staticMethod called\n"; }
}
$myArray = array();
$myArray['instanceOfMyClass'] = new MyClass;
$myArray['instanceOfMyClass']::staticMethod(); // works
class RunCode
{
private $myArray;
public function __construct(){
$this->myArray = array();
$this->myArray['instanceOfMyClass'] = new MyClass;
$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
}
}
new RunCode;
Any ideas on how to get around this?
You actually can use "->" to call static method:
$this->myArray['instanceOfMyClass']->staticMethod();
This is a really interesting problem, it may even be a bug in PHP itself.
For a work around, use the KISS principle.
class RunCode
{
private $myArray;
public function __construct(){
$this->myArray = array();
$this->myArray['instanceOfMyClass'] = new MyClass;
$instance = $this->myArray['instanceOfMyClass']
$instance::staticMethod();
}
}
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With