Yoav Kadosh
Yoav Kadosh

Reputation: 5155

Late static binding in older PHP versions

Consider the following scenario:

interface Validatable {
     static function validate($input);
}

class Field implements Validatable {
     static function validate($input) {
          return $input;
     }
}

Then, I call the function statically:

Field::validate($input);

But I Get the following error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

I know what the error means: T_PAAMAYIM_NEKUDOTAYIM stands for double colon in hebrew, which means thet the double colon is a syntax error. But how would I call a static function, without double colons?

NOTE: This works fine in PHP versions 5.4/5.3. The problem is with versions 5.2/5.1. How can the issue be fixed without updating the PHP version?

Upvotes: 0

Views: 104

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

See this comment on the docs page for interfaces. It looks like you're still on PHP <=5.2 and don't have access to Late Static Binding.

A workaround would be to not make the function static:

<?php
interface Validatable {
     function validate();
}

class Field implements Validatable {
    protected $input;

    function __construct($input) {
        $this->input = $input;
    }
     function validate() {
          return $this->input;
     }
}

$field = new Field('input');

var_dump($field->validate());

Edit

If you must have a static method, a general workaround is to use an inner method that calls to your static method using the keyword self:

<?php

interface Validatable {
     static function validate($input);
}

class Field implements Validatable {
     static function myValidate($input) {
         return self::validate($input);
     }

    static function validate($input) {
        return $input;
    }
}

print_r(Field::myValidate('test'));

I'm not 100% sure this will work in your case, but you can give it a try. I was able to get this to run at http://phptester.net/

Upvotes: 1

Related Questions