Nette\Object::getClassName()

Notice: This thread is very old.
juzna.cz
Member | 248
+
0
-

I miss a feature in PHP, which would allow me to reference classes easily. For example in Java, if you have a class cz.juzna.abc.Acticle and you wanna give it to a variable/method, you can reference it by cz.juzna.abc.Acticle.class.

In PHP, this can be done only by a string with class name ("cz\juzna\abc\Article"), which is however a string and not a reference. For example IDE won't see it as usage of a class (i.e. it won't autocomplete, won't find it in usages, …). This makes it very easy to make errors or typos in such definitions, or break the system while refactoring.

Therefore I suggest adding a new convenience method to Nette\Object, which would act in this way.

<?php
abstract class Object {
  static function getClassName() {
    return get_called_class();
  }
}
?>

With this, I can use cz\juzna\abc\Article::getClassName().

What do you think?

juzna.cz
Member | 248
+
0
-

Actually, I just noticed that I can use cz\juzna\abc\Article::getReflection()->name which would do it, but it's just not that straightforward and nice.

HosipLan
Moderator | 4668
+
0
-

I can see your reasons, but isn't that just overcomplicating things?

juzna.cz
Member | 248
+
0
-

Best would be having support in vanilla PHP, but we can't expect that. And passing strings is not really a good idea, especially when they're not constants. So easy to make a mistake there. And also you have to type it all, and with full name. No way for autocompletion or imported classes by use :(

Last edited by juzna.cz (2011-12-11 21:16)

David Grudl
Nette Core | 8138
+
0
-

This is really a missing feature in PHP, something like MyClass::__CLASS. But this is the topic for PHP forum, not Nette.

juzna.cz
Member | 248
+
0
-

Sure, but it's very useful! And we can wait couple of years before someone adds it to PHP and it gets deployed, or we can add it to Nette within 5minutes.
I added this to my Nette fork and have been using this for two weeks, and it's SO useful to have it in every class, with IDE's hints as well. Especially if you work with ORM like Doctrine.

If you're using ORM and if you type class names often, try it for a while and you'll see.