Objects
To create a new object, use the new statement to instantiate a class:
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.
Resources
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.
Converting to resource
As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.
Freeing resources
Thanks to the reference-counting system introduced with PHP 4’s Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.
Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector.
NULL
The special NULL value represents a variable with no value. NULL is the only possible value of type null.
A variable is considered to be null if:
- it has been assigned the constant NULL.
- it has not been set to any value yet.
- it has been unset().
There is only one value of type null, and that is the case-insensitive constant NULL.
Casting to NULL
Casting a variable to null using (unset) $var will not remove the variable or unset its value. It will only return a NULL value.
Callbacks
Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.
Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.
Passing
A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass ‘ClassName::methodName’.
Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.
Example: Callback function examples
</a>
<a href=”https://shahjalalhossain.files.wordpress.com/2014/01/screen-shot-2014-01-12-at-1-04-13-pm.png”>
Example: Callback example using a Closure
The above example will output:
2 4 6 8 10
Note: In PHP 4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.
Note: Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback.
Pseudo-types and variables used in this documentation
mixed
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.
number
number indicates that a parameter can be either integer or float.
callback
callback pseudo-types was used in this documentation before callable type hint was introduced by PHP 5.4. It means exactly the same.
void
void as a return type means that the return value is useless. void in a parameter list means that the function doesn’t accept any parameters.
$… in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.
Type Juggling
PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.
An example of PHP’s automatic type conversion is the addition operator ‘+’. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.
To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.
To test any of the examples in this section, use the var_dump() function.
Note: The behaviour of an automatic conversion to array is currently undefined.
Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:
Type Casting
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
The casts allowed are:
- (int), (integer) – cast to integer
- (bool), (boolean) – cast to boolean
- (float), (double), (real) – cast to float
- (string) – cast to string
- (array) – cast to array
- (object) – cast to object
- (unset) – cast to NULL (PHP 5)
- (binary) casting and b prefix forward support was added in PHP 5.2.1
Note: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.
Variables
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
Note: $this is a special variable that can’t be assigned
By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable’s value to another, changing one of those variables will have no effect on the other.
PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, “becomes an alias for” or “points to”) the original variable. Changes to the new variable affect the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs ‘My name is Bob’ twice:
One important thing to note is that only named variables may be assigned by reference.
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used – booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.
Warning In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.
Variable scope
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.
The global keyword
First, an example use of global:
Example Using global
The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:
Example: Using $GLOBALS instead of global
The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal.
Note: Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.
Using static variables
Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
Example: Example use of static variables
Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:
Example: Static variables with recursive functions
Note: Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.
Example: Declaring static variables
Note: Static declarations are resolved in compile-time.
References with global and static variables
The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
The above example will output:
null
object(stdClass)[1]
A similar behavior applies to the static statement. References are not stored statically:
The above example will output:
Static object:
null
Static object:
null
Static object:
null
Static object:
object(stdClass)[3]
public 'property' => int 1
This example demonstrates that when assigning a reference to a static variable, it’s not remembered when you call the &get_instance_ref() function a second time.
add a note add a note
Variable variables
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
$$a = 'world';
At this point two variables have been defined and stored in the PHP symbol tree: $a with contents “hello” and $hello with contents “world”. Therefore, this statement:
echo "$a ${$a}";
produces the exact same output as:
echo "$a $hello";
i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.
Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).
Example: Variable property example
class foo {
var $bar = 'I am bar.';
var $arr = array('I am A.', 'I am B.', 'I am C.');
var $r = 'I am r.';
}
$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->$baz[1] . "\n";
$start = 'b';
$end = 'ar';
echo $foo->{$start . $end} . "\n";
$arr = 'arr';
echo $foo->$arr[1] . "\n";
echo $foo->{$arr}[1] . "\n";
The above example will output:
I am bar.
I am bar.
I am bar.
I am r.
I am B.
Warning Please note that variable variables cannot be used with PHP’s Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
Variables From External Sources
Note: Dots and spaces in variable names are converted to underscores. For example becomes $_REQUEST[“a_b”].
Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It’s “PHP!”) will automagically become (It\’s \”PHP!\”). It was deemed that this was needed for escaping for DB insertion circa a decade ago and is a legacy feature now that should be disabled. See also addslashes(), stripslashes() and magic_quotes_sybase.