PHP 8.5.0 Released!

Voting

: min(eight, zero)?
(Example: nine)

The Note You're Voting On

deadimp at gmail dot com
17 years ago
I think this will be pretty helpful too.
My question is, can just 'static' by itself resolve to the late static class?
I ask this because it could help in making new instances of the derived class, from a base class, by calling a derived class's static method instead of having to create a new instance of the derived class - or explicitly defining a 'getClass' method for each derived class.
Example:
<?php
//There isn't really any purpose for this example I posted
//Just a random implementation
class Base {
    static function useful() {
        //Create a list of instances of the derived class
        $list=array();
        for ($i=0;$i<10;$i++) $list[]=new static(); //Here's the point in question
        return $list;
    }
}
class Derived extends Base {
    static function somethingElse() {
        //...
        $list=static::useful();
    }
}
?>
I'm not sure what kind of lexical / whatever-it's-called problems this would make with parsing. I don't think it could really collide with any contexts where you would use static otherwise - variable / method declaration.

Even more so, is there a way to get the class's name to which the keywords 'self', 'parent', or 'static' refer?
Example:
<?php
class Base {
    static function stuff() {
        echo "Self: ".get_class(self);
        echo "Parent: ".get_class(parent);
        echo "Derived: ".get_class(static);
    }
}
class Derived extends Base {
    static function stuff() {
        static::stuff();
    }
}
?>

I don't think there should be a massive bloat in the PHP core to support all of this, but it would be nice to take advantage of the dynamic nature of PHP.

And yet another side note:
If you're in the instance-level scope in a method of a base, and you want to get a top-level static, here's an ugly workaround (from Thacmus /lib/core.php - see SVN repo):
<?php
//Get reference [?] to static from class
    //$class - Class name OR object (uses get_class())
    //$var - Not gonna say
function& get_static($class,$var) { //'static_get'?
    if (!is_string($class)) $class=get_class($class);
    if (!@property_exists($class,$var)) {
        trigger_error("Static property does not exist: $class::\$$var");
        //debug_callstack(); //This is just a wrapper for debug_backtrace() for HTML
        return null;
    }
    //Store a reference so that the base data can be referred to
        //The code [[ return eval('return &'.$class.'::$'.$var.';') ]] does not work - can not return references...
        //To establish the reference, use [[ $ref=&get_static(...) ]]
    eval('$temp=&'.$class.'::$'.$var.';'); //using
    return $temp;
}
?>

<< Back to user notes page

To Top