PHP: Doing some cool things with references and destructors

php-logo
Not everybody of you might know, that there are references in PHP too, like in many other languages. I wondered if there is something these references might be really good for and came up with the following concept.

References

Maybe i should first tell you something about references in PHP:
Normally, you do not use any of them in your code. You need to use the "&" Operator to create references.
Maybe take a look at the following code to understand:

$a = 'test';
$b = & $a;
$a = 'abc';
echo $b; // Will output 'abc'

Object Destructors

Another important point to know is, when does PHP call the destructor of a object?
PHP does reference counting, that means, if there is no reference pointing at a object, the garbage collector will destroy the object, but before he does so, the __destruct() method of the object will be called.
Some example code for understanding:

class a {
  public function __destruct() {
    echo "I go now, bye!";
  }
}
$a = new a();
unset($a); // Will output "I go now, bye!"

Concept

If i combine the two things we know now, how about using references to do some normally impossible things? Like using something to manage references and use our destructor to manipulate the reference that pointed to us before we get destructed?

I realized this with some code you can find here: https://github.com/JuliusBeckmann/PHP-Reference-Fun

To do so, created the following classes:

ReferenceManager
This static class will collect references, we might use again.

ReferenceType
A abstract class that uses the ReferenceManager to manipulate the outside reference that pointed at us before we got destructed.

Idea: Write protected objects

WriteProtected extends ReferenceType
This class uses the ReferenceType destructor call, to recreate itself via the outside reference fetched from ReferenceManager.

Take a look at the source code to fully understand: ExampleWriteProtected.php

Idea: Static typed objects

AbstractStaticType extends ReferenceType
Another thing to know, when our destructor get called, there is no outside reference to out object any more. If there was only, the value it pointed to got overwritten by the new assigned value.
This can be used to manipulate the new value to something we want to have.

Take a look at the source to fully understand: ExampleStaticTypes.php

Conclusion

This whole concept is just a idea proven with some experimental code.
I think there could be several more useful things that can be done with this concept that might help in real life coding hell, but till now, i will just look at it as a neat idea to keep in mind for later.

No related posts.


 
 
 

Die Kommentarfunktion zu diesem Beitrag wurde deaktiviert.