note 47424 deleted from language.types.object by googleguy
| From: | googleguy@php.net | Date: | Wed, 16 Jan 2013 05:34:25 +0000 |
| Subject: | note 47424 deleted from language.types.object by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-193099@lists.php.net to get a copy of this message | ||
Note Submitter: sirbinam at nospam dot please dot hotmail dot com
----
<?php
class hack{}
$hack =& new hack;
class profiler{
function profiler(){
$this->startime = microtime();
}
function dump(){
global $hack;
$this->endtime = microtime();
$duration = $this->endtime - $this->starttime; /* this won't actually work, it just
the concept */
$stdout->write($duration);
}
}
class stdout{
function write($msg){
echo $msg;
}
}
$stdout =& new stdout();
$hack =& $stdout;
$profiler->dump();
?>
/*
*
* In short this little hack allows us to call $stdout->write() from
* $profiler->dump
*
* The problem is that $stdout doesn't exist yet and when the compiler
* parses this class, it sends a fatal error and dies because you can't
* refer to a method of an object that doesn't exist yet, even though
* this method doesn't get called until the end of execution, when the
* method does exist.
* This is the same as not being able to use a function before it is
* at least declared in say a header file. This is seen in C, Perl,
* and pretty much every language known to man. (TTBOMK?)
*
* So what does this hack do?
* The first thing that happens in the global scope is an empty class
* definition, it then creates a object called $hack from this class.
* All this does is allocate memory for an object, and places a pointer
* at the begining of that memory segment.
* When the compiler parses this class, it doesn't care that the $hack
* object is empty, as long as it has somewhere to assign a function
* pointer. Later in global scope the $stdout object is created.
* After $stdout is created, we do $hack =& $stdout. The =&
* (assign by reference) moves the pointer for $hack to the begining of
* the memory segment for $stdout. So when we call $hack->write(), it
* points to the exact same object->method() as $stdout->write(). So
* this is actually very reliable, just don't tell a purist!
*/