php - Confusion about namespace and use
代言
代言 2017-06-24 09:42:35
0
3
996

I have some doubts when using namespace and use
In the framework, just use someone with namespace(namespace) file, you can instantiate the object directly new

However, when I made a local directory test,
found that when calling a file with namespace,
cannot be referenced directly using the use method. Instantiation
But you must first require
before you can instantiate it normally

However, when I checked the framework, I found that there seemed to be no file to requrie to be instantiated in advance, but use can be instantiated directly after new Okay, what’s the reason for this?

Attach your own local test directory file
Directory structure

library
    -->core.php
test.php

core.php

<?php 
namespace library;

class core
{

}

test.php

<?php 

require_once 'library/core.php';  // 必须要require
// 第一种实例化
// use \library\core;
// $obj = new core();
// 第二种实例化
$obj = new \library\corecore();
var_dump($obj);

Attached are some screenshots of use in the framework

I can’t figure it out...I can’t figure it out...

Thank you for your answers, I must not have taken any medicine in the morning, eh! Final post~

Add some common sense about loading classes
spl_autoload_register($callback);

    /**
     * 自动加载类库
     * @param  string $strClass 方法名
     */
    static public function load($strClass) 
    {
        $strClassPath = CHARM . '\' .$strClass . APPEXT;
        if(in_array($strClass, self::$arrClassMap)) {
            return TRUE;
        }else {
            if(is_file($strClassPath)) {
                require_once $strClassPath;
                self::$arrClassMap[$strClass] = $strClass;
            }else {
                throw new \Exception("找不到类库 -- " . $strCtrlFile);
            }
        }
    }    
代言
代言

reply all(3)
刘奇
框架使用了自动加载机制

实现原理
spl_autoload_register($callable);
或
__autoload($callable);

这个函数注册了一个函数,在当前文件找不到对应的类时将自动调用,
执行其回调函数,将new的类include进来
某草草

Registration and self-loading https://github.com/TIGERB/eas...

为情所困

The poster uses the CI framework. The framework has already helped you spl_autoload_register($callable); in layman's terms, whichever class you use, it will help you require_once which class
For specific code implementation, you can look at this CI Loader class https://github.com/bcit-ci/Co...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template