实例化对象以在静态访问器中使用

Background

I have two classes, A and B, where A is a class which is full of static methods (Behat/Mink step definitions), but using logic methods from an instance of class B.

What I want is to have class A be able to use methods from an instance of B, A will have no constructor.

class A {
    // This class needs an instance of B, but A has no constructor

    const B_INSTANCE = new B(); //Surely not?
}

class B {
    public function __construct() {}

    public function methodForUseInClassA() {...}
}

Nuance

Right now, I have A extending B, but for unit testing purposes, instantiating B would be a better solution.

Question

How can I facilitate this? Is there some accepted best practice for this?

Any tips appreciated!

Either try to extend class A extends B {}, then you'll have access to the methods of B. Or try this one:

class A {
    //This class needs an instance of B, but A has no constructor
    private static $instanceOfB = null;

    // singleton returns always the same object while script is running
    public static function getInstanceOfB() {
        if( self::$instanceOfB === null ) {
            self::$instanceOfB = new B();
        }

        return self::$instanceOfB;
    }

    // always returns a new instance
    public static function getNewInstanceOfB() {
        return new B();
    }
}

class B {
    public function __construct() {}

    public function methodForUseInClassA() {
        // do something
    }

}

You can call it like this, but I think extending is the better option, except you just need some static helper methods.

$b = A::getInstanceOfB();
$b->methodForUseInClassA();