7
abstract class db_table {

    static function get_all_rows() {
        ...
        while(...) {
            $rows[] = new self();
            ...
        }
        return $rows;
    }
}

class user extends db_table {

}

$rows = user::get_all_rows();

I want to create instances of a class from a static method defined in the abstract parent class but PHP tells me "Fatal error: Cannot instantiate abstract class ..." How should I implement it correctly?

Edit: Of course I want to create instances of the class "user" in this case, not of the abstract class. So I've to tell it to create an instance of the called sub-class.

2 Answers 2

11

See this page in the manual:

Limitations of self::

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined.

There is only an easy way around this using PHP >= 5.3 and late static bindings. In PHP 5.3 this should work:

static function get_all_rows() {
        $class = get_called_class();
        while(...) {
            $rows[] = new $class();
            ...
        }
        return $rows;
    }

http://php.net/manual/en/function.get-called-class.php

Sign up to request clarification or add additional context in comments.

1 Comment

Hint: The get_called_class can be emulated in PHP < 5.3 by using this code: php.net/manual/en/function.get-called-class.php#93799
9

this work for me..

abstract class db_table {

static function get_all_rows() {
    ...
       while(...) {
           $rows[] = new static();
           ...
       }
       return $rows;
    }
}

1 Comment

Nice and elegant, liked it a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.