Re: New Feature: Fully qualified class name resolution as scalar with class keyword

From: Date: Tue, 17 Apr 2012 09:17:05 +0000
Subject: Re: New Feature: Fully qualified class name resolution as scalar with class keyword
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-60067@lists.php.net to get a copy of this message
On Sat, Apr 14, 2012 at 9:50 PM, Ralph Schindler <ralph@ralphschindler.com> wrote: > Hi all, > > There are many different use cases were in code we expect classes names as > arguments to functions as fully qualified names.  We do this in ZF a lot > with our Service Location and DI components, but also with our code > reflection API, etc.  A more interesting use case I would like to call out > is with PHPUnit, for example in a test, you might find this: > >  $mock = $this->getMock('A\Namespaced\ClassName'); > > This becomes cumbersome when you are dealing with lots of strings about lots > of class names.  This is also an area where, currently, namespace > declaration and use statements offer no real support. > > The patch located here: > > > https://github.com/ralphschindler/php-src/commit/02210d51851a96d723fbedcfc64cde9f9ae2b22a > > ... implements the ability for a developer to leverage the file's namespace > declaration and use statements to be able to produce a scalar (string) of > the class name that can be then used, for example, as an argument to a > function elsewhere. > > This overloads the "class" keyword, and by virtue of the existing usage of > "class" this feature is completely backwards compatible.  All existing tests > pass.  For example, the above PHPUnit snipped would become: > >  use A\Namespaced\ClassName; >  $mock = $this->getMock(ClassName::class); > > Another example with reflection: > >  use SomeOther\FullyNamespaced\ClassElsewhere as CE; >  $r = new ReflectionClass(CE::class); > > More examples from the test file: > >  namespace Foo\Bar { >    class Baz {} >    var_dump(Moo::CLASS); // "Foo\Bar\Moo" >  } > >  namespace { >    use Bee\Bop as Moo, >        Foo\Bar\Baz; > >    var_dump(Baz::class); // "Foo\Bar\Baz" >    var_dump(Boo::class); // "Boo" >    var_dump(Moo::CLASS); // "Bee\Bop" >    var_dump(\Moo::Class); // "Moo" > >    $class = Baz::class; // assign class as scalar to var >    $x = new $class; >    var_dump($x);  object(Foo\Bar\Baz)#1 (0) {} >  } > > > What do you guys think? Hey Ralph! I like the proposal :) A quick note on the patch: As the class name is compile-time resolvable it should in my eyes also be available as a static_scalar, so that it can be used in initialization lists: public function doFoo($withClass = ABC::class) { new $withClass; // or whatever } To be available as both a static_scalar and a general scalar one should put the rule in the common_scalar section. What do you think? Nikita

« previous php.internals (#60067) next »