note 119983 added to language.namespaces.faq
| From: | shaun at slickdesign dot com dot au | Date: | Tue, 04 Oct 2016 07:20:49 +0000 |
| Subject: | note 119983 added to language.namespaces.faq | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-206741@lists.php.net to get a copy of this message | ||
When creating classes or calling static methods from within namespaces using variables, you need to
keep in mind that they require the full namespace in order for the appropriate class to be used; you
CANNOT use an alias or short name, even if it is called within the same namespace. Neglecting to
take this into account can cause your code to use the wrong class, throw a fatal missing class
exception, or throw errors or warnings.
In these cases, you can use the magic constant __NAMESPACE__, or specify the full namespace and
class name directly. The function class_exists also requires the full namespace and class name, and
can be used to ensure that a fatal error won't be thrown due to missing classes.
<?php
namespace Foo;
class Bar {
public static function test() {
return get_called_class();
}
}
namespace Foo\Foo;
class Bar extends \Foo\Bar {
}
var_dump( Bar::test() ); // string(11) "Foo\Foo\Bar"
$bar = 'Foo\Bar';
var_dump( $bar::test() ); // string(7) "Foo\Bar"
$bar = __NAMESPACE__ . '\Bar';
var_dump( $bar::test() ); // string(11) "Foo\Foo\Bar"
$bar = 'Bar';
var_dump( $bar::test() ); // FATAL ERROR: Class 'Bar' not found or Incorrect class \Bar
used
----
Server IP: 72.52.91.14
Probable Submitter: 211.26.34.121
----
Manual Page -- http://php.net/manual/en/language.namespaces.faq.php
Edit -- https://master.php.net/note/edit/119983
Del: integrated -- https://master.php.net/note/delete/119983/integrated
Del: useless -- https://master.php.net/note/delete/119983/useless
Del: bad code -- https://master.php.net/note/delete/119983/bad+code
Del: spam -- https://master.php.net/note/delete/119983/spam
Del: non-english -- https://master.php.net/note/delete/119983/non-english
Del: in docs -- https://master.php.net/note/delete/119983/in+docs
Del: other reasons-- https://master.php.net/note/delete/119983
Reject -- https://master.php.net/note/reject/119983
Search -- https://master.php.net/manage/user-notes.php