Note that there are some explanatory texts on larger screens.

plurals
  1. POBasic autoload and namespace in php
    primarykey
    data
    text
    <p>I'm in the process of updating a framework that I wrote a while ago. I would like to adopt new standards such as namespaces and using the autoload feature.</p> <p>Right now my framework has a very rudimentary but functional autoload function that looks like this:</p> <pre><code>protected function runClasses() { $itemHandler = opendir( V_APP_PATH ); while( ( $item = readdir( $itemHandler ) ) !== false ) { if ( substr( $item, 0, 1 ) != "." ) { if( !is_dir( $item ) &amp;&amp; substr( $item, -10 ) == ".class.php" ) { if( !class_exists( $this-&gt;registry-&gt;$item ) ) { require_once( V_APP_PATH . $item ); $item = str_replace( ".class.php", "", $item ); $this-&gt;registry-&gt;$item = new $item( $this-&gt;registry ); } } } } } </code></pre> <p>As you can see in the code this function is limited to a single folder only, but the advantage to it is it loads the class into my registry allowing me to access that specific class in other files by doing something similar to <code>$this-&gt;registry-&gt;Class-&gt;somevar</code> which is the functionality I need.</p> <p>What I'm needing/wanting to accomplish is to use the autoloader function but have that function not limited to a single folder, instead be able to navigate through multiple folders and instantiate the needed classes. </p> <p>I have just some test files going and here is my current file structure:</p> <p><img src="https://i.stack.imgur.com/kI4V0.png" alt="File Structure"></p> <p>For MyClass2 I have:</p> <pre><code>namespace model; Class MyClass2 { function __construct() { echo "MyClass2 is now loaded!"; } } </code></pre> <p>For MyClass1 I have:</p> <pre><code>Class MyClass1 { function __construct() { echo "MyClass1 is now loaded!&lt;br /&gt;"; } } </code></pre> <p>And for Autoload I have:</p> <pre><code>function __autoload( $className ) { $file = $className . ".php"; printf( "%s &lt;br /&gt;", $file ); if(file_exists($file)) { require_once $file; } } $obj = new MyClass1(); $obj2 = new model\MyClass2(); </code></pre> <p>My Question is the way that is set up it can't find the file for MyClass2 so I'm wondering what I've done wrong and secondly, is there a way like my first "autoload" function to not need to specify the namespace in the autoload file and assign it to my registry?</p> <p>Sorry for such a lengthy question but any help is greatly appreciated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload