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 classesspl_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);
}
}
}
怪我咯2017-06-24 09:44:35
框架使用了自动加载机制
实现原理
spl_autoload_register($callable);
或
__autoload($callable);
这个函数注册了一个函数,在当前文件找不到对应的类时将自动调用,
执行其回调函数,将new的类include进来
为情所困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...