简体   繁体   中英

How do I use global namespace type hinting inside of a namespaced class in PHP 5.3+?

namespace MyClass\Util;

class Sample {

  public function each(Object $f) {

  }
}

From Calling File (not namespaced)

$sample = new Sample();
$sample->each(new stdClass());

Produces:

Catchable fatal error: Argument 1 passed to MyClass\\Util\\Sample.php must be an instance of MyClass\\Util\\Object, instance of Object given

You can use \\ to point to the global namespace :

namespace MyClass\Util;

class Sample {

  public function each(\Object $f) {

  }
}


As a reference, you can read Global space (quoting) :

Prefixing a name with \\ will specify that the name is required from the global space even in the context of the namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM