Home > Backend Development > PHP Tutorial > PHP automatic loading

PHP automatic loading

WBOY
Release: 2016-07-29 09:02:17
Original
941 people have browsed it

Automatic loading of classes

In external pages, there is no need to introduce class files, but the program will automatically "dynamically load" a class when it needs it.

  • When creating an object new
  • directly use a class name (to operate static properties and methods)

Use the __autoload magic function
When two situations occur, this function will be called. This function requires us to define it in advance and write a general statement for loading class files in it

<code><span><span>function</span><span>__autoload</span><span>(<span>$name</span>)</span>{</span><span>require</span><span>'./lib/'</span>.<span>$name</span>.<span>'.class.php'</span>;
}</code>
Copy after login

Use spl_autoload_register()
Use it to register (declare) multiple functions that can replace __autoload(). Naturally, you have to define these functions, and the functions of the functions are the same as __autoload(), but you can deal with more situations at this time

<code><span>//注册用于自动加载的函数</span>
spl_autoload_register(<span>"model"</span>);
spl_autoload_register(<span>"controll"</span>);
<span>//分别定义两个函数</span><span><span>function</span><span>model</span><span>(<span>$name</span>)</span>{</span><span>$file</span> = <span>'./model/'</span>.<span>$name</span>.<span>'.class.php'</span>;
    <span>if</span>(file_exists(<span>$file</span>)){
        <span>require</span><span>'./model/'</span>.<span>$name</span>.<span>'.class.php'</span>;
    }
}
<span>//如果需要一个类,但当前页面还没加载该类</span><span>//就会依次调用model()和controll(),直到找到该类文件加载,否则就报错</span><span><span>function</span><span>controll</span><span>(<span>$name</span>)</span>{</span><span>$file</span> = <span>'./controll/'</span>.<span>$name</span>.<span>'.class.php'</span>;
    <span>if</span>(file_exists(<span>$file</span>)){
        <span>require</span><span>'./controll/'</span>.<span>$name</span>.<span>'.class.php'</span>;
    }
}</code>
Copy after login
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

The above has introduced the automatic loading of PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template