[]RSS

About Archives Artwork Comic Contact Philosophy Projects Tags

Php, foot, mouth

September 27th, 2006 in Php. Weblog

I found an interesting behaviour tonight. The language allows you to call a member function as if it were a static function, something you can accidentally hide when calling callback functions:

// Oops, this calls a non-static member statically as sm::blocks
preg_replace_callback(
       "/(?<=\n\n|\r\n\r\n|\r\r|\A)(.*?)(?:\n\n|\r\n\r\n|\r\r|\Z)/sm",
       array("sm", "blocks"),
       $text);
}

What I really meant was:

array($this, "blocks")

When you call a static function in a Php class, it has the side-effect of wiping out the class context. Without the class context, you can’t make other calls to class members. In my case above, Php allowed me to break the class context (calling a non-static as static) without warning, which caused a perfectly legitimate class member function fail:

function text($m) {
    $this->inlines($m);
}

Which fails with: Using $this when not in object context.

Instead, Php should warn: Calling a non-static member as static. This might not be what you meant to do.

2 Responses to “Php, foot, mouth”

  1. apike says:
    September 27th, 2006 at 10:53 pm

    Do you have PHP 5 turned on? The object-orient stuff is a lot better in v5.

  2. mx says:
    September 28th, 2006 at 7:22 am

    Yes, I should have said this was in Php 5. The error is expected really, it could just use a warning on the non-static static call.

 

Leave a Reply

Subscribe to comments