talideon.com

Blackout Ireland

January 19, 2009 at 2:13PM I feel myself wanting to type ‘return new self($args)’ from as static method

I know this is a little silly, but I feel myself wanting to do something like this in a piece of code I’m writing:

abstract class Base {

    protected $arg;

    public function __construct($arg) {
        $this->arg = $arg;
    }

    public abstract function stuff();

    public static function wrap($arg) {
        // Here be the magic.
        return new Wrapper(new self($arg));
    }
}

class Wrapper {

    private $wrapped;

    public function __construct(Base $wrapped) {
        $this->wrapped = $wrapped;
    }

    public function nonsense() {
        return sprintf("[%s]\n", $this->wrapped->stuff());
    }
}

class A extends Base {

    public function stuff() {
        return strtoupper($this->arg);
    }
}

class B extends Base {

    public function stuff() {
        return strtolower($this->arg);
    }
}

echo A::wrap('Foo')->nonsense();
echo B::wrap('Bar')->nonsense();

Which would give:

[FOO]
[bar]

Of course, PHP doesn’t allow self to be (ab)used like that, and I’m sure there’s a much better way of achieving something similar to this, but I thought I’d record this particular brainfart for posterity anyway.