How to determine user defined function parameters names before calling it? - php

In PHP, I have created a user defined function. Example:
<?php
function test($one, $two) {
// do things
}
?>
I would like to find the names of the function parameters. How would I go about doing this?
This is an example of what I would like:
<?php
function test($one, $two) {
// do things
}
$params = magic_parameter_finding_function('test');
print_r($params);
?>
This would output:
Array
(
[0] => one
[1] => two
)
Also this is very important that I am able to get the user defined function parameter names outside the scope of the function. Thanks in advance!

You can do this using reflection...
$reflector = new ReflectionFunction('test');
$params = array();
foreach ($reflector->getParameters() as $param) {
$params[] = $param->name;
}
print_r($params);

you can use count_parameter a php built in function

Related

Is it possible to make a PHP function that would take any number of arguments?

I am writing some PHP code that would generate HTML files from templates.
I would like, if possible, to make a function that would take any strings I feed the function with, and put that into the file. Like so:
function generator($a, $b, $c, $n...){
$filename = $a . ".html";
ob_start ();
echo $b;
echo $c;
echo $d;
echo $n...;
$buffer = ob_get_clean();
file_put_contents($a, $buffer);
}
I need this, because different pages would have different number of include files, and with this I would be able to skip making different functions for specific pages. Just an iterator, and that's it.
Thanks!
From PHP 5.6+ you can use ... to indicate a variable number of arguments:
function test (... $args)
{
foreach ($args as $arg) {
echo $arg;
}
}
test("testing", "variable"); // testing variable
Demo
Variable-length argument lists from the manual
So, your function would look something like this:
function generator($a, $b, $c, ... $n) {
$filename = $a . ".html";
ob_start();
echo $b;
echo $c;
foreach ($n as $var) {
echo $var;
}
$buffer = ob_get_clean();
file_put_contents($a, $buffer);
}
You can also use variadic functions (PHP 5.6+) :
function generator($a, ...$args) {
echo $a . "\n";
print_r($args);
}
generator("test", 1, 2, 3, 4);
Outputs :
"test"
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
You can make it using an array as following :
function generator($array){
// set the first item of the array as name of the .html file and take it out of the array.
$filename = array_shift($array) . ".html";
ob_start ();
// echo all the array fields
foreach($array as $a){
echo $a;
}
$buffer = ob_get_clean();
file_put_contents($a, $buffer);
}
You can pass the array directly to call the function like the following :
generator( ["val_1", "val_2", "val_3"] );
Just use func_get_args(); inside your function to return an array of all arguments passed in.
You can also use func_get_arg($arg_num) to return a specific argument, or func_num_args to return the number of arguments.
All PHP functions allow any number of parameters, they just won't be callable by name, the only way is with these 3 functions.
Note, you may use a variadic argument as the last in the parameter list like so:
function my_func($x,$y, ... $z){
//Now $z is an array of all arguments after the first two
}
In the process of good design, I would think carefully about when and where to use things such as this. For example I currently work on a project that probably has over 200K lines of code and for better of worse this is actually never used.
The most common way is to pass an array "struct" to the method:
$args = array();
$args['kitchen'] = 'sink';
$args['bath'] = 'room';
$args['cat'] = array('fur','tail');
$func->someFunction($args);
If you wanted to have more control over the data you could create a struct and access that within the class. Public functions act as handlers.
class SomeClass {
....
private $args
public function setArgs($arg1,$arg2,$arg3) {
$this->arg1 = $arg1;
...
}
public function getArgs() {
return $this->args;
}
More rarely you can have C++ like control where you use a class just as a struct:
class MyStruct {
public $foo;
public $bar;
private $secret;
private function getSecret() {
return $secret;
}
protect function setSecret($val) {
$secret = $val;
}
}
Already mentioned is '...' which I nearly never see but it's interesting, though how useful ? Does this help explain what is going on?
function someFunction(... $args)
Usually you will see a mix of things in methods which helps articulate the purpose of it.
private function someSmallFunc($list = array(), $val = '', $limit = 10)
This example is to illustrate the natural grouping of information, data is in a list, $val is used for something to control the method along with $limit say limits the number of query results. Hence, you should think in this way about your methods IMO.
Also if you notice default values are set ($limit = 10) to in case they aren't passed in. For example if you call someSmallFunc($data, $someVal) (opposed to say someSmallFunc($data, $someVal, 20) ) and not pass in $limit it will default to 10.

Why getPostParameters doesn't work on symfony 1.4?

I have a form in symfony 1.4 which are created for each competence. My forms was created with success. But when I try to save my form I can't. I go to see my action code and the function getPostParameters seem dosn't work. I use getParameterHolder to see what's wrong in my parameters but after I put the good value the getPostParameters function doesn't work.
This is what I get from getParameterHolder:
sfParameterHolder Object
([parameters:protected] => Array
(
[professionnal_competence] => Array
(
[rayon_competence3] => 24
[rayon_competence9] => 22
[rayon_competence19] => 32
)
[module] => professionnal_subregion
[action] => saveCompetenceRadius
)
)
And my function:
public function executeSaveCompetenceRadius(sfWebRequest $request) {
$user = $this->getUser()->getGuardUser();
$q = ProfessionnalCompetenceQuery::create()
->addSelect('pc.*')
->where('pc.professionnal_id= ?', $user->getId());
$res = $q->execute();
$values = $request->getPostParameters(['professionnal_competence']);
$test = $request->getParameterHolder();
var_dump($values); print_r($values); print_r($request->getParameterHolder());
exit;
foreach ($res as $professionnalCompetence) {
foreach ($values['professionnal_competence'] as $k => $val) {
if ($k == 'rayon_competence' . $professionnalCompetence->getCompetenceId()) {
$professionnalCompetence->setRayonCompetence($val);
$professionnalCompetence->save();
}
}
}
return $this->renderComponent('professionnal_subregion', 'competenceRadius');
// return "test";
//return $this->renderPartial('professionnal_subregion/competenceradius');
}
This is my form:
class ProfessionnalCompetenceRadiusForm extends BaseProfessionnalCompetenceForm {
public function configure()
{
unset($this['rayon_competence']);
$this->widgetSchema['rayon_competence'.$this->object->getCompetenceId()] = new sfWidgetFormSelectUISlider(array('max'=>50,'step'=>1));
$this->widgetSchema->setHelp('rayon_competence'.$this->object->getCompetenceId(),'en kilomètres');
$this->widgetSchema->setLabel('rayon_competence'.$this->object->getCompetenceId(),'rayon');
$this->setValidator('rayon_competence'.$this->object->getCompetenceId(), new sfValidatorInteger(array('max'=>50)));
}
}
Someone has an idea or can help me ?? Because I try lot of thing but without success. Thank in advance :).
I think the error hides in this line:
$values = $request->getPostParameters(['professionnal_competence']);
You're passing an array to a function that takes a string. Try removing the brackets around 'professionnal_competence'.
EDIT: Scratch that. getPostParameters takes no parameters. getPostParameter, on the other hand, takes two - the first of which is the field name - a string. So, your code should be:
$values = $request->getPostParameter('professionnal_competence');
The error is here:
$values = $request->getPostParameters(['professionnal_competence']);
The function sfWebRequest::getPostParameters doesn't actually take parameters.
You can either access this array with [...], or use getPostParameter, which allows "safe" deep access:
$val = $request->getPostParameter('a[b]');
// basically the same as, but with error checks:
$val = $request->getPostParameters()['a']['b'];

How to get function's parameters names in PHP?

I'm looking for a sort of reversed func_get_args(). I would like to find out how the parameters were named when function was defined. The reason for this is I don't want to repeat myself when using setting variables passed as arguments through a method:
public function myFunction($paramJohn, $paramJoe, MyObject $paramMyObject)
{
$this->paramJohn = $paramJohn;
$this->paramJoe = $paramJoe;
$this->paramMyObject = $paramMyObject;
}
Ideally I could do something like:
foreach (func_get_params() as $param)
$this->${$param} = ${$param};
}
Is this an overkill, is it a plain stupid idea, or is there a much better way to make this happen?
You could use Reflection:
$ref = new ReflectionFunction('myFunction');
foreach( $ref->getParameters() as $param) {
echo $param->name;
}
Since you're using this in a class, you can use ReflectionMethod instead of ReflectionFunction:
$ref = new ReflectionMethod('ClassName', 'myFunction');
Here is a working example:
class ClassName {
public function myFunction($paramJohn, $paramJoe, $paramMyObject)
{
$ref = new ReflectionMethod($this, 'myFunction');
foreach( $ref->getParameters() as $param) {
$name = $param->name;
$this->$name = $$name;
}
}
}
$o = new ClassName;
$o->myFunction('John', 'Joe', new stdClass);
var_dump( $o);
Where the above var_dump() prints:
object(ClassName)#1 (3) {
["paramJohn"]=>
string(4) "John"
["paramJoe"]=>
string(3) "Joe"
["paramMyObject"]=>
object(stdClass)#2 (0) {
}
}
Code snippet that creates an array containing parameter names as keys and parameter values as corresponding values:
$ref = new ReflectionFunction(__FUNCTION__);
$functionParameters = [];
foreach($ref->getParameters() as $key => $currentParameter) {
$functionParameters[$currentParameter->getName()] = func_get_arg($key);
}
While it's not impossible to do it, it's usually better to use another method. Here is a link to a similar question on SO :
How to get a variable name as a string in PHP?
What you could do is pass all your parameters inside of an object, instead of passing them one by one. I'm assuming you are doing this in relation to databases, you might want to read about ORMs.
get_defined_vars will give you the parameter names and their values, so you can do
$params = get_defined_vars();
foreach ($params as $var=>$val) {
$this->${var} = $val;
}

Dynamically call Class with variable number of parameters in the constructor

I know that it is possible to call a function with a variable number of parameters with call_user_func_array() found here -> http://php.net/manual/en/function.call-user-func-array.php . What I want to do is nearly identical, but instead of a function, I want to call a PHP class with a variable number of parameters in it's constructor.
It would work something like the below, but I won't know the number of parameters, so I won't know how to instantiate the class.
<?php
//The class name will be pulled dynamically from another source
$myClass = '\Some\Dynamically\Generated\Class';
//The parameters will also be pulled from another source, for simplicity I
//have used two parameters. There could be 0, 1, 2, N, ... parameters
$myParameters = array ('dynamicparam1', 'dynamicparam2');
//The instantiated class needs to be called with 0, 1, 2, N, ... parameters
//not just two parameters.
$myClassInstance = new $myClass($myParameters[0], $myParameters[1]);
You can do the following using ReflectionClass
$myClass = '\Some\Dynamically\Generated\a';
$myParameters = array ('dynamicparam1', 'dynamicparam2');
$reflection = new \ReflectionClass($myClass);
$myClassInstance = $reflection->newInstanceArgs($myParameters);
PHP manual: http://www.php.net/manual/en/reflectionclass.newinstanceargs.php
Edit:
In php 5.6 you can achieve this with Argument unpacking.
$myClass = '\Some\Dynamically\Generated\a';
$myParameters = ['dynamicparam1', 'dynamicparam2'];
$myClassInstance = new $myClass(...$myParameters);
I implement this approach a lot when function args are > 2, rather then end up with an Christmas list of arguments which must be in a specific order, I simply pass in an associative array. By passing in an associative array, I can check for necessary and optional args and handle missing values as needed. Something like:
class MyClass
{
protected $requiredArg1;
protected $optionalArg1;
public function __construct(array $options = array())
{
// Check for a necessary arg
if (!isset($options['requiredArg1'])) {
throw new Exception('Missing requiredArg1');
}
// Now I can just localize
$requiredArg1 = $options['requiredArg1'];
$optionalArg1 = (isset($options['optionalArg1'])) ? $options['optionalArg1'] : null;
// Now that you have localized args, do what you want
$this->requiredArg1 = $requiredArg1;
$this->optionalArg1 = $optionalArg1;
}
}
// Example call
$class = 'MyClass';
$array = array('requiredArg1' => 'Foo!', 'optionalArg1' => 'Bar!');
$instance = new $class($array);
var_dump($instance->getRequiredArg1());
var_dump($instance->getOptionalArg1());
I highly recommend using an associative array, however it is possible to use a 0-index array. You will have to be extremely careful when constructing the array and account for indices that have meaning, otherwise you will pass in an array with offset args and wreck havoc with your function.
You can do that using func_get_args().
class my_class {
function __construct( $first = NULL ) {
$params = func_get_args();
if( is_array( $first ) )
$params = $first;
// the $params array will contain the
// arguments passed to the child function
foreach( $params as $p )
echo "Param: $p\n";
}
}
function my_function() {
$instance = new my_class( func_get_args() );
}
echo "you can still create my_class instances like normal:";
$instance = new my_class( "one", "two", "three" );
echo "\n\n\n";
echo "but also through my_function:";
my_function( "one", "two", "three" );
Basically, you simply pass the result of func_get_args to the constructor of your class, and let it decide whether it is being called with an array of arguments from that function, or whether it is being called normally.
This code outputs
you can still create my_class instances like normal:
Param: one
Param: two
Param: three
but also through my_function:
Param: one
Param: two
Param: three
Hope that helps.
I've found here
Is there a call_user_func() equivalent to create a new class instance?
the example:
function createInstance($className, array $arguments = array())
{
if(class_exists($className)) {
return call_user_func_array(array(
new ReflectionClass($className), 'newInstance'),
$arguments);
}
return false;
}
But can somebody tell me if there is an example for classes with protected constructors?

Can we pass an array as parameter in any function in PHP?

I have a function to send mail to users and I want to pass one of its parameter as an array of ids.
Is this possible to do? If yes, how can it be done?
Suppose we have a function as:
function sendemail($id, $userid) {
}
In the example, $id should be an array.
You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside.
function sendemail($id, $userid){
// ...
}
sendemail(array('a', 'b', 'c'), 10);
You can in fact only accept an array there by placing its type in the function's argument signature...
function sendemail(array $id, $userid){
// ...
}
You can also call the function with its arguments as an array...
call_user_func_array('sendemail', array('argument1', 'argument2'));
even more cool, you can pass a variable count of parameters to a function like this:
function sendmail(...$users){
foreach($users as $user){
}
}
sendmail('user1','user2','user3');
Yes, you can safely pass an array as a parameter.
Yes, you can do that.
function sendemail($id_list,$userid){
foreach($id_list as $id) {
printf("$id\n"); // Will run twice, once outputting id1, then id2
}
}
$idl = Array("id1", "id2");
$uid = "userID";
sendemail($idl, $uid);
What should be clarified here.
Just pass the array when you call this function.
function sendemail($id,$userid){
Some Process....
}
$id=array(1,2);
sendmail($id,$userid);
function sendemail(Array $id,$userid){ // forces $id must be an array
Some Process....
}
$ids = array(121,122,123);
sendmail($ids, $userId);
Its no different to any other variable, e.g.
function sendemail($id,$userid){
echo $arr["foo"];
}
$arr = array("foo" => "bar");
sendemail($arr, $userid);
I composed this code as an example. Hope the idea works!
<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
function greetings($friends){
echo "Greetings, $friends <br>";
}
foreach ($friends as $friend) {
greetings($friend);
}
?>
I found Delcon answer helpful but I was looking for this
function sendmail($user1, $user2, $user3){
echo $user1;
echo $user2;
echo $user3;
}
$users = array('user1','user2','user3');
sendmail(...$users);
In php 5, you can also hint the type of the passed variable:
function sendemail(array $id, $userid){
//function body
}
See type hinting.
Since PHP is dynamically weakly typed, you can pass any variable to the function and the function will try to do its best with it.
Therefore, you can indeed pass arrays as parameters.
Yes, we can pass arrays to a function.
$arr = array(“a” => “first”, “b” => “second”, “c” => “third”);
function user_defined($item, $key)
{
echo $key.”-”.$item.”<br/>”;
}
array_walk($arr, ‘user_defined’);
We can find more array functions here
http://skillrow.com/array-functions-in-php-part1/
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

Categories