New trick for PHP, passing by ref!

I started my development career scripting PHP 4 .  This was my first dive into programming and pretty much had to figure it out as I went.  Many years later, I turned to the c# language and have not looked back since.

This past week, I was approached to help someone with an issue in PHP.  The error, PHP Deprecated:  Assigning the return value of new by reference is deprecated in…, would indicate that the there was a problem in the code.  Upon my investigation, I found this in the code…

list($w, $h) = explode('x', $_GET['s']);
$ci =& new CropInterface();

What I found is that from PHP version 5.3 on, the assignment of a variable to a new object instance is done by reference automatically.  This is somewhat a new theory for me because the idea of passing by reference was not in my thought process back when working in PHP.  And quite frankly I did not even know that was an option up until this point.

For more information on passing by reference in PHP, feel free to look at the link below…


One thought on “New trick for PHP, passing by ref!

  1. References in PHP are somewhat inconsistent and occasionally awkward. For example, you can’t pass a static variable by reference, but a function/method is able to receive said variable as a reference and it will behave in the expected manner.

    Matters are confused further by the misinformation surrounding how PHP handles variables internally. It’s often claimed that “x is done by reference automatically” where this is in fact not true. Variables are not passed or assigned by reference, but are instead internally treated as “pointers” while appropriate (copy on write i.e. until the data is modified, it’s more efficient to “point to” the source data for as long as read-only access is necessary, to prevent unnecessary duplication of data; this is not a functional reference in the typical sense). In the case of objects, the value of a variable becomes an identifier for the (instance of the) object to be used if the variable is treated as an object, but it is not a reference and does not fully behave like a reference.

    Despite their difficulties, references can be very useful and efficient and are worth keeping in mind.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s