导入类与设置命名空间

导入类与设置命名空间

以下的类都是为了说明而已,不重要,可以直接跳到index.php中。

  • File.php
namespace Page5\File;

class Index{
    public function getFile(){
        return "File";
    }
}
  • Page.php
namespace Page5\Page;

class Page{
    public function getPage(){
        return "Page";
    }
}
  • function.php
class Index{
    static public function getName(){
        return "name\n";
    }
}
  • index.php
namespace Page5\Index;
// 这里都需要先把对应的类倒入到该文件中
require_once "./File.php";
require_once "./Page.php";
require_once "./function.php";
// 设置了命名空间的别名
use Page5\File as File;
// 倒入类本身
use Page5\Page\Page as Page;

class Index{
    public $file;
    public $page;
    // 注意,当为命名空间设置别名时,调用对应的类时,需要加上对应的别名
    public function __construct(File\Index $file)
    {
        $this->file=$file;
    }
    // 但是当导入类时,只需要调用对应的类名就行了
    public function setPage(Page $page){
        $this->page=$page;
    }
    static public function getName(){
        // 注意这里有一个常量:__NAMESPACE__
        return __NAMESPACE__." name\n";
    }
}

$index=new Index(new File\Index());
print $index->file->getFile()."\n";
$index->setPage(new Page());
print $index->page->getPage()."\n";
// 注意,这里有一个类没有设置命名空间,但是类名与定义了命名空间的类一致,所以需要加上\的注释
print Index::getName();
print \Index::getName();

各个文件均在同一个目录下

猜你喜欢

转载自blog.csdn.net/YQXLLWY/article/details/82944812