lifeclot // say all that you can. . .

$this is Out of Context

Thursday, March 25, 2010Technology

I’ve stumbled across some strange behavior in PHP 5 when calling a class method statically from an Exception’s constructor. In PHP, you’re not required to label a class’s function as static but you are still able to use it as a static function. Example:


<?php

class MyClass {
    public function 
MyFunction() {
        echo 
"You called MyClass's MyFunction";
    }
}

MyClass::MyFunction();

?>

Now, the strange little … behavior I have noticed is that when you call a method statically from an instance of an Exception’s constructor, $this always references the instance of the Exception object. Example:


<?php

class ExtendedException extends Exception {
    public function 
__construct($message$code) {
        
parent::__construct($message$code);
        
        
Log::Write("Hello!");
    }
}

class 
Log {
    
// Note this method is not marked static
    
public function Write($string) {
        
print_r($this);
    }
}

try {
    throw new 
ExtendedException();
} catch (
Exception $e) { }

?>

So check it out. print_r($this); outputs the ExtendedException object’s properties:


ExtendedException Object
(
    [message:protected] => 
    [string:Exception:private] => 
    [code:protected] => 0
    [file:protected] => D:\Projects\Public\bugtest.php
    [line:protected] => 17
    [trace:Exception:private] => Array
        (
        )

    [previous:Exception:private] => 
)

This will only occur if you do not label the method-to-be-called-statically as static; otherwise you’ll get a 500.

Interesting, eh?

Tags: ,

Leave a Reply

You must be logged in to post a comment.