Home > php教程 > php手册 > php的spl

php的spl

WBOY
Release: 2016-06-06 19:45:16
Original
1240 people have browsed it

在php5中的标准库方法spl_autoload相当于实现自己的__autoload ? php function __autoload( $classname ){ if ( is_file ( $classname .'.php' ){ include $classname .'.php' ; } elseif ( is_file ( $classname .'.inc' ){ include $classname .'.inc' ; }

在php5中的标准库方法spl_autoload相当于实现自己的__autoload

<span>php
    </span><span>function</span> __autoload(<span>$classname</span><span>){
        </span><span>if</span>(<span>is_file</span>(<span>$classname</span>.'.php'<span>){
            </span><span>include</span> <span>$classname</span>.'.php'<span>;
        } </span><span>elseif</span>(<span>is_file</span>(<span>$classname</span>.'.inc'<span>){
            </span><span>include</span> <span>$classname</span>.'.inc'<span>;
        }
    }</span>
Copy after login

它会在注册目录下自动寻找与$classname同名的.php/.inc文件。当然,你也可以指定特定类型的文件,方法是注册扩展名

<span>php
    spl_autoload_extensions(</span>'.php,.inc,.some');
Copy after login

这样,它也会搜索.some文件。默认,php是不会启动spl_autoload的,那么怎样才能自动让spl_autoload生效呢呢?方法是

<span>php
    spl_autoload_register();</span>
Copy after login

spl_autoload_register有一个$callback参数,如果不指定,它就会自动注册spl_autoload,为了能搜寻更多的自动加载目录,可以在这些代码前面设置自动加载目录

<span>php
    </span><span>set_include_path</span>(<span>get_include_path</span>() . PATH_SEPARATOR . 'some/path' . DIRECTORY_SEPARATOR);
Copy after login

这样,当php找不到指定的类时,就会在set_include_path指定的目录下寻找。

这些方法常用在php框架中。比如把上面的介绍串连起来:

<span>set_include_path</span>(<span>get_include_path</span>() . PATH_SEPARATOR . 'some/path' .<span> DIRECTORY_SEPARATOR);
spl_autoload_extensions(</span>'.php,.inc,.some'<span>);
spl_autoload_register();</span></p>

<p>当你要加载some/path下面的classA类时,它会在目录下寻找classa.php或classa.inc或classa.some,这样你就可以放心地运用new classA或extends classA</p>
<p></p>
<pre class="brush:php;toolbar:false"><span>php
    ClassB </span><span>extends</span><span> ClassA {
        </span><span>//</span><span> code..</span>
<span>    }

    </span><span>$a</span> = <span>new</span><span> ClassA;
    </span><span>$b</span> = <span>new</span> ClassB;
Copy after login
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template