1

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 !

1
  • 3
    What does not work as expected? Commented Mar 21, 2011 at 21:01

1 Answer 1

8
<?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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.