Namespace in PHP CodeIgniter Framework

后端 未结 4 1502
温柔的废话
温柔的废话 2020-11-28 09:32

Does CodeIgniter support Namespace?

4条回答
  •  春和景丽
    2020-11-28 10:12

    How To Get Namespaces to Work in Codeigniter

    Actually, you can get namespaces to work in conjunction to relative paths in your application models. This modification makes loading models much easier and also allows you to have interfaces...

    Add this to the end of your application/config/config.php

    spl_autoload_extensions('.php'); // Only Autoload PHP Files
    
    spl_autoload_register(function($classname) {
        if (strpos($classname,'\\') !== false) {
            // Namespaced Classes
            $classfile = strtolower(str_replace('\\', '/', $classname));
    
            if ($classname[0] !== '/') {
                $classfile = APPPATH.'models/' . $classfile . '.php';
            }               
            require($classfile);
        } elseif (strpos($classname, 'interface') !== false) {
            // Interfaces
            strtolower($classname);
            require('application/interfaces/' . $classname . '.php');
        }
    });
    

    Example Namespaced Class:

    foobar;
        }
    
        public function setFoobar($val) {
            $this->foobar = $val;
        }
    
    }
    

    Example Instantiation of Class in Your Code Somewhere:

    IMPORTANT NOTE: DO NOT USE BUILT IN CI_Loader ( Ex: $this->load->model(); )

    // This will Autoload Your Namespaced Class
    $example = new foo\Bar();
    

    or alternatively on top of your PHP class (ex: controller, other model), you can do this...

    Example of Interface:

提交回复
热议问题