johnlemon
johnlemon

Reputation: 21449

PHP 5.3 namespaces - functions not working as expected

There are some functions not working properly with namespaces

<?php
namespace MyApp;
class Fruit {}
class Apple extends Fruit {}

$apple = new Apple();
$name = 'Apple';

var_dump (is_subclass_of($apple, 'Fruit'));
var_dump (is_a($apple, 'Apple'));
var_dump (new $name);

How can I make this compatible with both php 5.3 and php < 5.3 with no namespace support ? is_subclass_of and is_a are not working like this !

Upvotes: 1

Views: 2411

Answers (1)

Charles
Charles

Reputation: 51411

<?php
namespace MyApp;
class Fruit {}
class Apple extends Fruit {}

$apple = new Apple();
$name = 'MyApp\Apple';

var_dump (is_subclass_of($apple, 'MyApp\Fruit'));
var_dump (is_a($apple, 'MyApp\Apple'));
var_dump (new $name);

You need to fully qualify your namespace name in functions that take a class name as a string instead of as a bareword. Classes as barewords are resolved at runtime. Here's the PHP manual on namespace resolution, and here's a page with examples using strings to fully qualify namespaces.

(Also note the single quotes to prevent backslash munching.)

Upvotes: 8

Related Questions