Custom Libraries and Codeigniter Namespaces

I am creating custom libraries for a project that I have migrated to the CI structure, and I had a problem when certain classes have the same name.

To get around this problem, I tried to implement namespaces to no avail. I do research, and I know that this would not have been possible in the past, but with a newer version of PHP, I was wondering if there is a way to do this, or if I am doing it right.

CI Version: 2.1.4 PHP Version: 5.4.12

Here is a demonstration of my installation:

applications / libraries / class1.php

<?

class class1{
   public function __construct()
    {
        $CI =& get_instance();

        $CI->load->library('foo/class2.php');
    }
}
?>

applications / libraries / Foo / class2.php

<?

namespace foo

class class2{

    function bar(){

    }

} 

?>

When I run the CI application, I will get the following error:

Nonexistent class: class2

Thanks for any help.

+4
4

, ,

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

.

.

CodeIgniter PHP4, - PHP5.

: PHP CodeIgniter Framework

+2

Codeigniter 2.x 3.x, , . , :

// you can still manually load in libraries like this
require_once(APPPATH.'libraries/foo/class2.php');

class class1 {

   public function __construct()
    {
        $CI =& get_instance();

        // instantiate the class2 and make it available for all of class1 methods
        $this->class2 = new foo/class2();
    }

}

, php, , php- .

+2

.

( ), "bootstrap", :

<?php

require_once(APPPATH.'libraries/foo/class2.php');

class class2 extends foo\class2 {}

"" , :

$this->load->library("class2");

$this->class2->bar(); // same as foo\class2->bar();
+1

, "load" , .

, load ('foo/class2') "foo" .

normaly, , "foo/bar".

I do not if the loading class supports this, although you may need to simply create a new object manually (this is what the load class does anyway, it includes a file and creates a new object).

0
source

Source: https://habr.com/ru/post/1531815/


All Articles