Dear Rasmus,

On Thu, Mar 14, 2013 at 5:26 PM, Rasmus Schultz <ras...@mindplay.dk> wrote:

> Hey List,
>
> What do you think about adding a typeof() operator to PHP?
>
> It could go something like this:
>
>     class User
>     {
>         public $name;
>     }
>
>     /**
>      * @var ReflectionClass $user_type
>      * @var ReflectionProperty $user_name_property
>      */
>
>     $user_type = typeof(User);
>
>     $user_name_property = typeof(User::$name);
>
> Mind you, this is an operator and not a function - User and User::$name are
> interpreted as symbols.
>
> This would allow for static analysis of class and property-references.
>
> Why? Because you can't use static analysis on code like this:
>
>     $user_type = new ReflectionClass('User');
>
>     $user_name_property = new ReflectionProperty('User', 'name');
>
> 'User' and 'name' are just strings, and strings are dead matter when it
> comes to static analysis.
>

It is certainly possible for static analyses to reason about literal
strings. Handling reflective code is not that hard when its arguments are
literals.


>
> Most form builders and ORMs (and other reflective meta-programming
> components) require references to properties or classes, e.g.:
>
>     $form->textInputFor($user, 'name');
>
> There is no knowledge that 'name' actually refers to the symbol User::$name
> and hence to way to perform static analysis or use refactoring tools on
> this code.
>
> Compare to:
>
>     $form->textInputFor($user, typeof(User::$name));
>


To me this code makes no sense. I expect typeof to return a type, since we
have no first-class types in PHP, I expect it to return a string
representing the type.

If I understand your example, here it returns a Reflection* ?

What about typeof($a->b) or even typeof($a->$foo) ? I assume both of them
would be forbidden ?



> This code can be analyzed and refactored, because the reference to the
> User::$name property is now literal.
>
>
Difficulty to statically analyze code comes from its dynamic nature, to me
typeOf(User::$name) is no less dynamic than new ReflectionProperty("User",
"name").


> Actually having to type out typeof() may not be the most elegant approach,
> and using this syntax it does resemble a function - having a more distinct
> syntax might be better.
>
> But those things aside, what do you think about having a way to statically
> reference types and members?


> Thanks,
>    Rasmus Schultz
>



-- 
Etienne Kneuss

Reply via email to