Tags
Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
Example: Valid and invalid constant names
// Valid constant names
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");
// Invalid constant names
define("2FOO", "something");
// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");
Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.
Syntax
You can define a constant by using the define()-function or by using the const keyword outside a class definition as of PHP 5.3.0. Once a constant is defined, it can never be changed or undefined.
Only scalar data (boolean, integer, float and string) can be contained in constants. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.
You can get the value of a constant by simply specifying its name. Unlike with variables, you should not prepend a constant with a $. You can also use the function constant() to read a constant’s value if you wish to obtain the constant’s name dynamically. Use get_defined_constants() to get a list of all defined constants.
Note: Constants and (global) variables are in a different namespace. This implies that for example TRUE and $TRUE are generally different.
If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs “CONSTANT”). An error of level E_NOTICE will be issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant). If you simply want to check if a constant is set, use the defined() function.
These are the differences between constants and variables:
- Constants do not have a dollar sign ($) before them;
- Constants may only be defined using the define() function, not by simple assignment;
- Constants may be defined and accessed anywhere without regard to variable scoping rules;
- Constants may not be redefined or undefined once they have been set; and
- Constants may only evaluate to scalar values.
Example: Defining Constants
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
Example: Defining Constants using the const keyword
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';
echo CONSTANT;
Magic constants
PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.
There are eight magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it’s used on in your script. These special constants are case-insensitive and are as follows:
A few “magical” PHP constants
- __LINE__ : The current line number of the file.
- __FILE__ : The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
- __DIR__ : The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
- __FUNCTION__ : The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
- __CLASS__ : The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
- __TRAIT__ : The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).
- __METHOD__ : The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
- __NAMESPACE__ : The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).
Operators
Operator Precedence
The precedence of an operator specifies how “tightly” it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication (“*”) operator has a higher precedence than the addition (“+”) operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.
Operators of equal precedence that are non-associative cannot be used next to each other, for example 1 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal, because the == operator has lesser precedence than the <= operator.
Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.
The division operator (“/”) returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
The result of the modulus operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a. For example:
echo (5 % 3)."\n"; // prints 2
echo (5 % -3)."\n"; // prints 2
echo (-5 % 3)."\n"; // prints -2
echo (-5 % -3)."\n"; // prints -2
Assignment by Reference
Assignment by reference is also supported, using the “$var = &$othervar;” syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.
Example #1 Assigning by reference
$a = 3;
$b = &$a; // $b is a reference to $a
print "$a\n"; // prints 3
print "$b\n"; // prints 3
$a = 4; // change $a
print "$a\n"; // prints 4
print "$b\n"; // prints 4 as well, since $b is a reference to $a, which has
// been changed
As of PHP 5, the new operator returns a reference automatically, so assigning the result of new by reference results in an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in earlier versions.
For example, this code will result in a warning:
class C {}
/* The following line generates the following error message:
* Deprecated: Assigning the return value of new by reference is deprecated in...
*/
$o = &new C;
Bitwise Operators
$a & $b : And : Bits that are set in both $a and $b are set.
$a | $b : Or (inclusive or) : Bits that are set in either $a or $b are set.
$a ^ $b : Xor (exclusive or) : Bits that are set in $a or $b but not both are set.
~ $a : Not : Bits that are set in $a are not set, and vice versa.
$a <> $b : Shift right : Shift the bits of $a $b steps to the right (each step means “divide by two”)
Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.
Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.
Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters’ ASCII values.
Comparison Operators
Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
For various types, comparison is done according to the following table (in order).
Comparison with Various Types
null or string – string : Convert NULL to “”, numerical or lexical comparison
bool or null – anything : Convert both sides to bool, FALSE < TRUE
object – object : Built-in classes can define its own comparison, different classes are uncomparable, same class – compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation
string, resource or number – string, resource or number : Translate strings and resources to numbers, usual math
array – array : Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise – compare value by value (see following example)
object – anything : object is always greater
array – anything : array is always greater
Example: Boolean/null comparison
// Bool and null are compared as bool always
var_dump(1 == TRUE); // TRUE - same as (bool)1 == TRUE
var_dump(0 == FALSE); // TRUE - same as (bool)0 == FALSE
var_dump(100 < TRUE); // FALSE - same as (bool)100 < TRUE
var_dump(-10 < FALSE);// FALSE - same as (bool)-10 < FALSE
var_dump(min(-100, -10, NULL, 10, 100)); // NULL - (bool)NULL < (bool)-100 is FALSE < TRUE
Warning Because of the way floats are represented internally, you should not test two floats for equality. See the documentation for float for more information.
Ternary Operator
Another conditional operator is the “?:” (or ternary) operator.
Example: Assigning a default value
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Note: Please note that the ternary operator is a statement, and that it doesn’t evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
Question 1: What would be the output of the following code segment?
//1.
$foo = TRUE;
$bar = $foo?:’FALSE’;
echo($bar);
//2.
$foo = FALSE;
$bar = $foo?:’FALSE’;
echo($bar);
A. TRUEFALSE
B. FALSEFALSE
C. 0FALSE
D. 1FALSE
*Answer will be available at the end of the post.
Error Control Operators
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");
// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
Execution Operators
PHP supports one execution operator: backticks (“). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won’t simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().
$output = `ls -al`;
echo "
$output
";
Note: The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.
Note: Unlike some other languages, backticks cannot be used within double-quoted strings.
Incrementing/Decrementing Operators
PHP supports C-style pre- and post-increment and decrement operators.
Note: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.
Increment/decrement Operators
++$a : Pre-increment – Increments $a by one, then returns $a.
$a++ : Post-increment – Returns $a, then increments $a by one.
–$a : Pre-decrement – Decrements $a by one, then returns $a.
$a– : Post-decrement – Returns $a, then decrements $a by one.
Incrementing or decrementing booleans has no effect.
Logical Operators
Logical Operators Example
$a and $b : And – TRUE if both $a and $b are TRUE.
$a or $b : Or – TRUE if either $a or $b is TRUE.
$a xor $b : Xor – TRUE if either $a or $b is TRUE, but not both.
! $a : Not – TRUE if $a is not TRUE.
$a && $b : And – TRUE if both $a and $b are TRUE.
$a || $b : Or – TRUE if either $a or $b is TRUE.
The reason for the two different variations of “and” and “or” operators is that they operate at different precedences. (See Operator Precedence.)
Example: Logical operators illustrated
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
// --------------------
// "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
var_dump($e, $f);
// --------------------
// "&&" has a greater precedence than "and"
// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;
// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;
var_dump($g, $h);
The above example will output something similar to:
bool(true)
bool(false)
bool(false)
bool(true)
String Operators
There are two string operators. The first is the concatenation operator (‘.’), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (‘.=’), which appends the argument on the right side to the argument on the left side.
Array Operators
$a + $b : Union – Union of $a and $b.
$a == $b : Equality – TRUE if $a and $b have the same key/value pairs.
$a === $b : Identity – TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $b : Inequality – TRUE if $a is not equal to $b.
$a $b : Inequality – TRUE if $a is not equal to $b.
$a !== $b : Non-identity – TRUE if $a is not identical to $b.
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
When executed, this script will print the following:
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Union of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
}
Elements of arrays are equal for the comparison if they have the same key and value.
Example: Comparing arrays
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
Type Operators
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:
Example: Using instanceof with classes
class MyClass
{
}
class NotMyClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
The above example will output:
bool(true)
bool(false)
instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:
Example: Using instanceof with inherited classes
class ParentClass
{
}
class MyClass extends ParentClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
The above example will output:
bool(true)
bool(true)
To check if an object is not an instanceof a class, the logical not operator can be used.
Example: Using instanceof to check if object is not an instanceof a class
class MyClass
{
}
$a = new MyClass;
var_dump(!($a instanceof stdClass));
The above example will output:
bool(true)
Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:
Example: Using instanceof for class
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
The above example will output:
bool(true)
bool(true)
Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:
Example:
Using instanceof with other variables
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
The above example will output:
bool(true)
bool(true)
bool(false)
instanceof does not throw any error if the variable being tested is not an object, it simply returns FALSE. Constants, however, are not allowed.
Example:
Using instanceof to test other variables
$a = 1;
$b = NULL;
$c = imagecreate(5, 5);
var_dump($a instanceof stdClass); // $a is an integer
var_dump($b instanceof stdClass); // $b is NULL
var_dump($c instanceof stdClass); // $c is a resource
var_dump(FALSE instanceof stdClass);
The above example will output:
bool(false)
bool(false)
bool(false)
PHP Fatal error:
instanceof expects an object instance, constant given
There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:
Example:
Avoiding classname lookups and fatal errors with instanceof in PHP 5.0
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
The above example will output:
bool(false)
The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.
See also get_class() and is_a().
Answers:
Question 1: D