Consider the following code:
error_reporting(E_STRICT);
class test {
function test_arr(&$a) {
var_dump($a);
}
function get_arr() {
return array(1, 2);
}
}
$t = new test;
$t->test_arr($t->get_arr());
This will generate the following output:
Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
The reason? The test::get_arr()
method is not a variable and under strict mode this will generate a warning. This behavior is extremely non-intuitive as the get_arr()
method returns an array value.
To get around this error in strict mode, either change the signature of the method so it doesn't use a reference:
function test_arr($a) {
var_dump($a);
}
Since you can't change the signature of array_shift
you can also use an intermediate variable:
$inter = get_arr();
$el = array_shift($inter);
Incrementing / Decrementing Operators
++
increment operator
--
decrement operator
Example Name Effect
---------------------------------------------------------------------
++$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.
These can go before or after the variable.
If put before the variable, the increment/decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done.
For example:
$apples = 10;
for ($i = 0; $i < 10; ++$i) {
echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}
Live example
In the case above ++$i
is used, since it is faster. $i++
would have the same results.
Pre-increment is a little bit faster because it really increments the variable and after that 'returns' the result. Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second's.
However, you must use $apples--
, since first, you want to display the current number of apples, and then you want to subtract one from it.
You can also increment letters in PHP:
$i = "a";
while ($i < "c") {
echo $i++;
}
Once z
is reached aa
is next, and so on.
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
Stack Overflow Posts:
Best Answer
You should remove the
&
(ampersand) symbol, so that line 4 will look like this:This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0