search

Home  >  Q&A  >  body text

php - Confusion about namespace and use

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);
            }
        }
    }    
代言代言2771 days ago1000

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-06-24 09:44:35

    框架使用了自动加载机制
    
    实现原理
    spl_autoload_register($callable);
    或
    __autoload($callable);
    
    这个函数注册了一个函数,在当前文件找不到对应的类时将自动调用,
    执行其回调函数,将new的类include进来
    

    reply
    0
  • 某草草

    某草草2017-06-24 09:44:35

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

    reply
    0
  • 为情所困

    为情所困2017-06-24 09:44:35

    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...

    reply
    0
  • Cancelreply