Php function name in var

Php function name in var

It may be worth specifically noting, if variable names follow some kind of «template,» they can be referenced like this:

// Given these variables .
$nameTypes = array( «first» , «last» , «company» );
$name_first = «John» ;
$name_last = «Doe» ;
$name_company = «PHP.net» ;

// Then this loop is .
foreach( $nameTypes as $type )
print $ < "name_ $type " >. «\n» ;

// . equivalent to this print statement.
print » $name_first \n $name_last \n $name_company \n» ;
?>

This is apparent from the notes others have left, but is not explicitly stated.

In addition, it is possible to use associative array to secure name of variables available to be used within a function (or class / not tested).

This way the variable variable feature is useful to validate variables; define, output and manage only within the function that receives as parameter
an associative array :
array(‘index’=>’value’,’index’=>’value’);
index = reference to variable to be used within function
value = name of the variable to be used within function

$vars = [ ‘id’ => ‘user_id’ , ’email’ => ‘user_email’ ];

function validateVarsFunction ( $vars )

//$vars[‘id’]=34; // define allowed variables
$user_id = 21 ;
$user_email = ’email@mail.com’ ;

echo $vars [ ‘id’ ]; // prints name of variable: user_id
echo $< $vars [ 'id' ]>; // prints 21
echo ‘Email: ‘ .$< $vars [ 'email' ]>; // print email@mail.com

// we don’t have the name of the variables before declaring them inside the function
>
?>

The feature of variable variable names is welcome, but it should be avoided when possible. Modern IDE software fails to interpret such variables correctly, regular find/replace also fails. It’s a kind of magic 🙂 This may really make it hard to refactor code. Imagine you want to rename variable $username to $userName and try to find all occurrences of $username in code by checking «$userName». You may easily omit:
$a = ‘username’;
echo $$a;

If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:

$price_for_monday = 10 ;
$price_for_tuesday = 20 ;
$price_for_wednesday = 30 ;

$price_for_today = $< 'price_for_' . $today >;
echo $price_for_today ; // will return 20
?>

PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

class Foo public function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$a = new $my_foo ();
$a -> hello (); //prints ‘Hello world!’
?>

Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

class Foo public static function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$my_foo :: hello (); //prints ‘Hello world!’
?>

You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: —

foreach ( $array as $key => $value )
$ $key = $value ;
>

?>

This however would be reinventing the wheel when you can simply use:

extract ( $array , EXTR_OVERWRITE );
?>

Note that this will overwrite the contents of variables that already exist.

Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: —

$array =array( «one» => «First Value» ,
«two» => «2nd Value» ,
«three» => «8»
);

extract ( $array , EXTR_PREFIX_ALL , «my_prefix_» );

?>

This would create variables: —
$my_prefix_one
$my_prefix_two
$my_prefix_three

containing: —
«First Value», «2nd Value» and «8» respectively

Another use for this feature in PHP is dynamic parsing..

Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created. In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.

Normally, you won’t need something this convolute. In this example, I needed to load an array with dynamically named objects — (yes, this has some basic Object Oriented programming, please bare with me..)

// this is only a skeletal example, of course.
$object_array = array();

// assume the $input array has tokens for parsing.
foreach ( $input_array as $key => $value ) <
// test to ensure the $value is what we need.
$obj = «obj» . $key ;
$ $obj = new Obj ( $value , $other_var );
Array_Push ( $object_array , $ $obj );
// etc..
>

?>

Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.

I haven’t fully tested the implimentation of the objects. The scope of a variable-variable’s object attributes (get all that?) is a little tough to crack. Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.

Then, we can easily pull everything back out again using a basic array function: foreach.

//.
foreach( $array as $key => $object )

echo $key . » — » . $object -> print_fcn (). »
\n» ;

?>

Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.

Источник

PHP Variable Functions

Summary: in this tutorial, you will learn about the PHP variable functions and how to use them to call a function, a method of an object, and a class’s static method.

Introduction to PHP variable functions

Variable functions allow you to use a variable like a function. When you append parentheses () to a variable, PHP will look for the function whose name is the same as the value of the variable and execute it. For example:

 $f = 'strlen'; echo $f('Hello');Code language: HTML, XML (xml)
  • First, define a variable $f and initialize its value to the ‘strlen’ literal string.
  • Second, use the $f as a function by passing the string ‘Hello’ to it.

When PHP sees $f() , it looks for the strlen() function. Because the strlen() is a built-in function, PHP just invokes it.

If PHP cannot find the function name, it’ll raise an error. For example:

 $f = 'len'; echo $f('Hello');Code language: HTML, XML (xml)
Fatal error: Uncaught Error: Call to undefined function len() in index.php:5Code language: plaintext (plaintext)

In this example, because PHP cannot find the len() function, it issues an error.

More variable function examples

Let’s take some examples of using the variable functions.

1) Using variable functions to call a method example

The variable functions allow you to call the methods of an object. The syntax for calling a method using a variable function is as follows:

$this->$variable($arguments)Code language: PHP (php)

Notice that you need to prefix the variable name with the $ sign. In this case, you’ll have the $ sign before the this keyword and the variable name. For example:

 class Str < private $s; public function __construct(string $s) < $this->s = $s; > public function lower() < return mb_strtolower($this->s, 'UTF-8'); > public function upper() < return mb_strtoupper($this->s, 'UTF-8'); > public function title() < return mb_convert_case($this->s, MB_CASE_TITLE, 'UTF-8'); > public function convert(string $format) < if (!in_array($format, ['lower', 'upper', 'title'])) < throw new Exception('The format is not supported.'); > return $this->$format(); > >Code language: HTML, XML (xml)
  • First, define a Str class that has three methods for converting a string to lowercase, uppercase, and title case.
  • Second, define the convert() method that accepts a string. If the format argument is not one of the method names: lower, upper, and title, the convert() method will raise an exception. Otherwise, it’ll call the corresponding method lower() , upper() or title() .

The following shows how to use the convert() method of the Str class:

 require_once 'Str.php'; $str = new Str('Hello there'); echo $str->convert('title');Code language: HTML, XML (xml)

2) Using variable functions to call a static method example

The following example uses a variable function to call a static method:

 class Str < private $s; public function __construct(string $s) < $this->s = $s; > public function __toString() < return $this->s; > public static function compare(Str $s1, Str $s2) < return strcmp($s1, $s2); > >Code language: HTML, XML (xml)

The Str class has a constructor that accepts a string. It implements the toString() method that converts the Str instance to a string.

The Str class has the compare() static method that compares two instances of the Str class. To call the compare() static method using a variable function, you use the following:

$str1 = new Str('Hi'); $str2 = new Str('Hi'); $action = 'compare'; echo Str::$action($str1, $str2); // 0Code language: PHP (php)

Summary

  • Append parentheses () to a variable name to call the function whose name is the same as the variable’s value.
  • Use the $this->$variable() to call a method of a class.
  • Use the className::$variable() to call a static method of a class.

Источник

Читайте также:  Html href link color css
Оцените статью