Extract $_GET/$_POST params and pass them to constructor
For example, $_GET
contains id=10, var=100
. How can I extract and pass them to constructor p开发者_StackOverflow中文版ublic function __construct($id, $var)
Something like this new Test(extract($_GET));
Use ReflectionMethod
from reflection API to check what's the signature of __construct()
method.
class MyClass {
public function __construct($id, $title, $slug = null) {
var_dump($id, $title, $slug);
}
}
$object = new MyClass();
$method = new ReflectionMethod($object, '__construct');
$parameters = $method->getParameters();
$parameters
contains an array of ReflectionParameter
objects.
Now you need to prepare an array of parameters that will be used by ReflectionMethod::invokeArgs()
:
$invokeParameters = array();
foreach ($parameters as $parameter) {
$value = $_REQUEST[$parameter->getName()];
$invokeParameters[$parameter->getPosition()] = $value;
}
$method->invokeArgs($object, $invokeParameters);
Of course you should add a few conditions to check whether all mandatory parameters exist within $_REQUEST
, throw exception if not, etc.
I presume you know what values you are looking for from the URL?
$_GET in PHP is just an associative array. So if my url looks like this:
http://example.com/index.php?var1=foo&var2=bar
I can get those variables like so:
new Test($_GET['var1'], $_GET['var2']);
Be careful with $_GET as there is no safeguard that prevents me from changing my URL bar to
http://example.com/index.php?var1=foo&var2=[malicious code]
So you should always treat it as untrusted.
Change the constructor to __construct($array); and the set you variables inside the construtor. It's not pretty and I would not recomend it, but it will work.
$_GET
is an associative array. So you could get the key from $_GET
to get the variable name. The value is obviously $_GET['key']
精彩评论