Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fully qualified interface name

Tags:

php

Is there a way to get fully qualified interface name similar to MyClass::class?

For example:

namespace Example\Tests;

use Example\Interfaces\InputInterface;
...

class CommandTest ...
...
public function createInputMock()
{
    // I want to replace next string with something similar to MyClass::class
    $this->getMockBuilder('Example\Interfaces\InputInterface')
...

Thank you.

like image 693
hadvig Avatar asked Dec 24 '22 12:12

hadvig


2 Answers

The ::class name resolution can work with any imported namespaces: classes, interfaces, functions, ...

namespace A\B\C {
    interface Interface_Bar {}
    function Function_Foo() {}
    function Function_Foo_Bar() {}
    const Const_BARFOO = 123;
}

namespace {
    use A\B\C\Interface_Bar;
    use A\B\C;
    use Undefined\Classes\UndefinedClass;
    use function A\B\C\Function_Foo_Bar;
    use const A\B\C\Const_BARFOO;

    echo Interface_Bar::class, "\n"; // print A\B\C\Interface_Bar
    echo C\Function_Foo::class, "\n"; // print A\B\C\Function_Foo
    echo C\Const_BARFOO::class, "\n"; // print A\B\C\Const_BARFOO
    echo UndefinedClass::class, "\n"; // print Undefined\Classes\UndefinedClass

    echo Function_Foo_Bar::class, "\n"; // print Function_Foo_Bar <- warning
    echo Const_BARFOO::class, "\n"; // print Const_BARFOO <- warning
}
like image 58
Federkun Avatar answered Dec 28 '22 11:12

Federkun


If I got you right, you can't move to PHP 5.5 with ::class notation, so you want to have something similar in your 5.4 or earlier vesrion.

So the short answer is — no, there is no way.

The lack of this functionality in the previous versions of PHP is what made core developers to add ::class to PHP 5.5.

You can make a weird dirty hack if it's a class name: using get_class on new instance, but don't do it.

like image 38
ksimka Avatar answered Dec 28 '22 09:12

ksimka