PHP $this

Recently an upgrade on my hosting server has been conducted, making a change from predominantly PHP4 (PHP5 available but not widely used) to predominantly PHP5 (PHP4 available but infrequently used). This has been prompted by the announcement by PHP developers that support for PHP4 will be discontinued at the end of the year.

I didn’t think there would be any issues with the migration as I have long been coding in a PHP5 compatible way, however after the move Halifax Online suffered a few issues. After much investigation I discovered that this was due to some deprecated code use within some functions in a party application which had been added to the site. This was easily fixed, but the issue its self is rather interesting.

It is common practice to store ephemeral data in loops and pass this data along to other loops or functions. While the actual variable name doesn’t matter so long as it is consistent, it makes sense to name it something which indicates that the data is for use only in situ and is ephemeral. The developer of the problematic application had used a variable named $this to perform this action.

Name wise this makes a lot of sense because it indicates quite clearly that the content of the variable is ephemeral and for use only in situ, especially with respect to functions. The problem is that $this is somewhat reserved under PHP5 and so while can be read from under ordinary circumstances, cannot be written to. This is because in an object orientated environment it is used to represent the current object in which a piece of code resides, and so changing it within this context has no meaning; changing attributes of it makes sense, but changing the whole thing (as the code was effectively doing by assigning it a value) is impossible. Can I demolish and rebuild my house while still inside it?

I just thought I’d share this little gem with folk who are trying to make their applications PHP5 compatible before the end of the year. It took me quite a while to find because I was looking primarily for deprecated function use, not variable use.

   

Comments are closed.