Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does PHP assignment operator do?

Tags:

php

memory

I happens to read this http://code.google.com/speed/articles/optimizing-php.html

It claims that this code

$description = strip_tags($_POST['description']);
echo $description;

should be optimized as below

echo strip_tags($_POST['description']);

However, in my understanding, assignment operation in PHP is not necessarily create a copy in memory.

This only have one copy of "abc" in memory.

$a = $b = "abc";

It consumes more memory only when one variable is changed.

$a = $b = "abc";
$a = "xyz";

Is that correct?

like image 737
Morgan Cheng Avatar asked Jun 04 '11 03:06

Morgan Cheng


People also ask

What does the assignment operator do?

The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.

What is an assignment operator give an example?

The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. Example of the Assignment Operators: A = 5; // use Assignment symbol to assign 5 to the operand A.

What is the meaning of -> in PHP?

The object operator, -> , is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.

What is the difference between := and assignment operators?

= operator assigns a value either as a part of the SET statement or as a part of the SET clause in an UPDATE statement, in any other case = operator is interpreted as a comparison operator. On the other hand, := operator assigns a value and it is never interpreted as a comparison operator.


2 Answers

should be optimized as below

It's only a good idea if you don't need to store it, thereby avoiding unnecessary memory consumption. However, if you need to output the same thing again later, it's better to store it in a variable to avoid a another function call.

Is that correct?

Yes. It's called copy-on-write.

like image 187
webbiedave Avatar answered Oct 09 '22 15:10

webbiedave


In the first example, if the variable is only used once then there is not point of making a variable in the first place, just echo the statements result right away, there is no need for the variable.

In the second example, PHP has something called copy on write. That means that if you have two variables that point to the same thing, they are both just pointing at the same bit of memory. That is until one of the variables is written to, then a copy is made, and the change is made to that copy.

like image 1
Mark Tomlin Avatar answered Oct 09 '22 14:10

Mark Tomlin