What does the "&" sign mean in PHP? [duplicate] - php

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 10 years ago.
I was trying to find this answer on Google, but I guess the symbol & works as some operator, or is just not generally a searchable term for any reason.. anyhow. I saw this code snippet while learning how to create WordPress plugins, so I just need to know what the & means when it precedes a variable that holds a class object.
//Actions and Filters
if (isset($dl_pluginSeries)) {
//Actions
add_action('wp_head', array(&$dl_pluginSeries, 'addHeaderCode'), 1);
//Filters
add_filter('the_content', array(&$dl_pluginSeries, 'addContent'));
}

This will force the variable to be passed by reference. Normally, a hard copy would be created for simple types. This can come handy for large strings (performance gain) or if you want to manipulate the variable without using the return statement, eg:
$a = 1;
function inc(&$input)
{
$input++;
}
inc($a);
echo $a; // 2
Objects will be passed by reference automatically.
If you like to handle a copy over to a function, use
clone $object;
Then, the original object is not altered, eg:
$a = new Obj;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1

The ampersand preceding a variable represents a reference to the original, instead of a copy or just the value.
See here: http://www.phpreferencebook.com/samples/php-pass-by-reference/

This passes something by reference instead of value.
See:
http://php.net/manual/en/language.references.php
http://php.net/manual/en/language.references.pass.php

I used it for sending a variable to a function, and have the function change the variable around. After the function is done, I don't need to return the function to the return value and set the new value to my variable.
Example
function fixString(&$str) {
$str = "World";
}
$str = "Hello";
fixString($str);
echo $str; //Outputs World;
Code without the &
function fixString($str) {
$str = "World";
return $str;
}
$str = "Hello";
$str = fixString($str);
echo $str; //Outputs World;

Related

how the value incresed without increasing in the this php code [duplicate]

This question already has answers here:
What does "&" mean in '&$var' in PHP? [duplicate]
(2 answers)
Closed 3 months ago.
<?php
function doSomething( &$arg ){
$return = $arg;
$arg += 1;
return $return;
}
$a = 3;
$b = doSomething( $a );
echo $a.' ';
echo $b;
?>
I know the answer a=4 and b=3 I understand how b= 3 but how come value of the a increased
The & operator tells PHP not to copy the variable when passing it to the function. Instead, a reference to the variable is passed into the function, thus the function modifies the original variable instead of a copy.
Therefore $arg += 1; will increase $a

Does PHP declares variables passed to functions args by reference? [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 10 years ago.
I was trying to find this answer on Google, but I guess the symbol & works as some operator, or is just not generally a searchable term for any reason.. anyhow. I saw this code snippet while learning how to create WordPress plugins, so I just need to know what the & means when it precedes a variable that holds a class object.
//Actions and Filters
if (isset($dl_pluginSeries)) {
//Actions
add_action('wp_head', array(&$dl_pluginSeries, 'addHeaderCode'), 1);
//Filters
add_filter('the_content', array(&$dl_pluginSeries, 'addContent'));
}
This will force the variable to be passed by reference. Normally, a hard copy would be created for simple types. This can come handy for large strings (performance gain) or if you want to manipulate the variable without using the return statement, eg:
$a = 1;
function inc(&$input)
{
$input++;
}
inc($a);
echo $a; // 2
Objects will be passed by reference automatically.
If you like to handle a copy over to a function, use
clone $object;
Then, the original object is not altered, eg:
$a = new Obj;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1
The ampersand preceding a variable represents a reference to the original, instead of a copy or just the value.
See here: http://www.phpreferencebook.com/samples/php-pass-by-reference/
This passes something by reference instead of value.
See:
http://php.net/manual/en/language.references.php
http://php.net/manual/en/language.references.pass.php
I used it for sending a variable to a function, and have the function change the variable around. After the function is done, I don't need to return the function to the return value and set the new value to my variable.
Example
function fixString(&$str) {
$str = "World";
}
$str = "Hello";
fixString($str);
echo $str; //Outputs World;
Code without the &
function fixString($str) {
$str = "World";
return $str;
}
$str = "Hello";
$str = fixString($str);
echo $str; //Outputs World;

What is meant by $$$var. IS it works in php [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 6 years ago.
I know what is $var and $$var will do. But in an interview they give me a problem which contains $$$var. What is that means actually. I cant find any reference for that.
It is Variable variables. This will make you understand:
<?php
$a = 123;
$b = 'a';
$var = 'b';
echo $var; //b
echo $$var; //a
echo $$$var; //123
Simply you can understand the flow:
$var is a variable and it hold value.
$$var means the new variable that name is the value of $var.
and $$$var means the new variable that name is the value of $$var.
example:
$var = 'app';
so $$var will be $app.
and so on.

PHP, $this->{$var} -- what does that mean?

I have encountered the need to access/change a variable as such:
$this->{$var}
The context is with CI datamapper get rules. I can't seem to find what this syntax actually does. What do the {'s do in this context?
Why can't you just use:
$this->var
This is a variable variable, such that you will end up with $this->{value-of-$val}.
See: http://php.net/manual/en/language.variables.variable.php
So for example:
$this->a = "hello";
$this->b = "hi";
$this->val = "howdy";
$val = "a";
echo $this->{$val}; // outputs "hello"
$val = "b";
echo $this->{$val}; // outputs "hi"
echo $this->val; // outputs "howdy"
echo $this->{"val"}; // also outputs "howdy"
Working example: http://3v4l.org/QNds9
This of course is working within a class context. You can use variable variables in a local context just as easily like this:
$a = "hello";
$b = "hi";
$val = "a";
echo $$val; // outputs "hello"
$val = "b";
echo $$val; // outputs "hi"
Working example: http://3v4l.org/n16sk
First of all $this->{$var} and $this->var are two very different things. The latter will request the var class variable while the other will request the name of the variable contained in the string of $var. If $var is the string 'foo' then it will request $this->foo and so on.
This is useful for dynamic programming (when you know the name of the variable only at runtime). But the classic {} notation in a string context is very powerful especially when you have weird variable names:
${'y - x'} = 'Ok';
$var = 'y - x';
echo ${$var};
will print Ok even if the variable name y - x isn't valid because of the spaces and the - character.

How to treat string as a string and not as an int in PHP

I was reading PHP manual and I came across type juggling
I was confused, because I've never came across such thing.
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
When I used this code it returns me 15, it adds up 10 + 5 and when I use is_int() it returns me true ie. 1 where I was expecting an error, it later referenced me to String conversion to numbers where I read If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero)
$foo = 1 + "bob3"; /* $foo is int though this doesn't add up 3+1
but as stated this adds 1+0 */
now what should I do if I want to treat 10 Little Piggies OR bob3 as a string and not as an int. Using settype() doesn't work either. I want an error that I cannot add 5 to a string.
If you want an error, you need to trigger an error:
$string = "bob3";
if (is_string($string))
{
trigger_error('Does not work on a string.');
}
$foo = 1 + $string;
Or if you like to have some interface:
class IntegerAddition
{
private $a, $b;
public function __construct($a, $b) {
if (!is_int($a)) throw new InvalidArgumentException('$a needs to be integer');
if (!is_int($b)) throw new InvalidArgumentException('$b needs to be integer');
$this->a = $a; $this->b = $b;
}
public function calculate() {
return $this->a + $this->b;
}
}
$add = new IntegerAddition(1, 'bob3');
echo $add->calculate();
This is by design as a result of PHP's dynamically typed nature and of course lack of an explicit type declaration requirement. Variable types are determined based on context.
Based on your example, when you do:
$a = 10;
$b = "10 Pigs";
$c = $a + $b // $c == (int) 20;
Calling is_int($c) will of course always evaluate to a boolean true because PHP has decided to convert the result of the statement to an integer.
If you're looking for an error by the interpreter, you won't get it since this is, like I mentioned, something built into the language. You might have to write a lot of ugly conditional code to test your data types.
Or, if you want to do that for testing arguments passed to your functions - that's the only scenario which I can think of where you might want to do this - you can trust the client invoking your function to know what they are doing. Otherwise, the return value can simply be documented to be undefined.
I know coming from other platforms and languages, that might be hard to accept, but believe it or not a lot of great libraries written in PHP follow that same approach.

Categories