php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #43302 Type hints do not respect imported namespaces
Submitted: 2007-11-15 02:27 UTC Modified: 2007-11-15 11:14 UTC
From: hans at velum dot net Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3CVS-2007-11-15 (snap) OS: Gentoo
Private report: No CVE-ID: None
 [2007-11-15 02:27 UTC] hans at velum dot net
Description:
------------
When using type hints, the namespaces that were imported (using "use") are not consulted to resolve the type-hinted class names.  i.e. if I have a class defined in namespace "foo::bar", it is assumed that *all* classes specified as type hints used in methods in my class are in the "foo::bar" namespace -- regardless of which other namespaces I import.

Reproduce code:
---------------
This is best illustrated with 3 files:

AClass.php:
<?php
namespace proj::a;
class AClass {}
?>

BClass.php:
<?php
namespace proj::b;
use proj::a;
class BClass {
  function setA(AClass $a) {}
}
?>

test.php:
<?php
require 'AClass.php';
require 'BClass.php';

$b = new proj::b::BClass();
$b->setA(new proj::a::AClass());
?>


Expected result:
----------------
No error.

Actual result:
--------------
Catchable fatal error: Argument 1 passed to proj::b::BClass::setA() must be an instance of proj::b::AClass, instance of proj::a::AClass given, called in test.php on line 6 and defined in BClass.php on line 5

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-11-15 09:43 UTC] felipensp at gmail dot com
This is expected.

README.namespaces:

7) qualified class names are interpreted as class from corresponding
namespace. So "new A::B::C()" refers to class C from namespace A::B.

...

<?php
namespace A;
new A(); // first tries to create object of class "A" from namespace "A" (A::A)
         // then creates object of internal class "A"
?>

Using:

use proj::a; with type hint a::AClass.
or
without 'use' with type hint proj::a::AClass.
or
use proj::a as x; with type hint x::AClass.

Works fine!
 [2007-11-15 11:14 UTC] hans at velum dot net
Ok, I think I see my error :)  I was assuming that "use proj::a;" would bring the classes within that namespace into my local scope, but clearly that is not the case.  Thanks for clarification.  I could have sworn that I had an example where that did work ... but if I did, I'll open another bug to discuss the inconsistency :)
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 16 16:01:34 2025 UTC