I am trying to call a method stored as $_auto
, but it will not work.
<?php
class Index {
private $_auto;
public function __construct() {
$this->_auto = "index";
$this->_auto();
}
public function index() {
echo "index";
}
}
$index = new Index();
?>
You code is trying to call a method called "_auto". To do what you are asking, you want to make the method name a php variable or something along the lines of what the other posters are saying.
You don't have a method named
_auto()
, you only have a property named$_auto
. If your intent is for a call to an undefined method to return a similarly named property if it exists, then you would need to write a__call()
magic method to perform the logic of looking at a similarly named property and returning the value. So something like this would need to be added to your class:I think you mistakenly defined "_auto" as a property?
Try using:
Instead of
You need to use
call_user_func
to do this:Unfortunately PHP does not allow you to directly use property values as callables.
There is also a trick you could use to auto-invoke callables like this. I 'm not sure I would endorse it, but here it is. Add this implementation of
__call
to your class:This will allow you to invoke callables, so you can call free functions:
And class methods:
And of course you can customize this behavior by tweaking what
__call
invokes.