Php variable variables object

PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example

After the execution of the statements above, the variable $txt will hold the value Hello world! , the variable $x will hold the value 5 , and the variable $y will hold the value 10.5 .

Note: When you assign a text value to a variable, put quotes around the value.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Think of variables as containers for storing data.

PHP Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ( $age and $AGE are two different variables)

Remember that PHP variable names are case-sensitive!

Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example

The following example will produce the same output as the example above:

Example

The following example will output the sum of two variables:

Example

Note: You will learn more about the echo statement and how to output data to the screen in the next chapter.

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

Читайте также:  Html coding utf 8

In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a «Fatal Error» on a type mismatch.

You will learn more about strict and non-strict requirements, and data type declarations in the PHP Functions chapter.

Источник

Php variable variables object

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
>
?>

Читайте также:  Python import all class

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_» );

Читайте также:  Php get all domains

?>

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.

Источник

Оцените статью