2011/1/5 Johannes Schlüter <johan...@php.net>

> On Wed, 2011-01-05 at 21:53 -0300, Martin Scotta wrote:
> > $obj = newInstance( MyClass ); // notice. undefined constant MyClass
>
> This describes the major change with your idea.
>
> What happens if a constant MyClass exists?
>
> Another question is something like this:
>
> <?php
> function  factory($class) {
>    return new $class();
> }
>
> factory( SomeClass );
> ?>
>
>
> To proper support this we'd have to make classes first class elements.
> For making this consistent it would make sense to make functions first
> class elements. And best drop the $ in front of variables and create a
> new language. Everything else becomes a mess.
>
> johannes
>
>
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
I think he's actually proposing creating for each class the magic class
constant CLASS, so your example becomes:

<?php

function factory($class) {
    return new $class();
}

factory( SomeClass::CLASS );

?>

This is actually doable without a magic class constant, but requires a
function or class constant to be declared in each class.

<?php
class SomeClass {
    const CLASS = __NAMESPACE__ . '\' . __CLASS__;
    static function getNameWithNSPath()
    {
        return __NAMESPACE__ . '\' . __CLASS__;
    }
}


factory( SomeClass::getNameWithNSPath() );
?>

Perhaps this could be simplified with traits, if __NAMESPACE__ and __CLASS__
work in traits that way. In fact, that's an interesting question, what is
__NAMESPACE__ in a trait defined in one namespace, then used in a class in a
different namespace?

I think the point is that the factory function could exist without any
knowledge of the namespaces of the classes it would work on. Then, somewhere
else where the class has been aliased or is otherwise accessible without the
full namespace path, the developer wouldn't need to specify the full
namespace path to the factory, but could ask the class itself what it's full
namespace path was. I don't know that I agree with the idea, but I don't
think it requires making classes first class elements.

John

Reply via email to