为什么PHP的自动加载功能无法在CLI模式下工作? [英] Why doesn't PHP's Autoload feature work in CLI mode?

查看:266
本文介绍了为什么PHP的自动加载功能无法在CLI模式下工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对我个人而言更重要,但这总是让我感到困扰:为什么特别是在CLI模式下PHP无法执行自动加载"?

This is more for my own personal edification than anything else but, this is something that has always bothered me: Why specifically can't PHP perform "autoloading" while in CLI mode?

多年以来,我一直在阅读免责声明,但从未读过任何与之相关的内容:

I've been reading this disclaimer for years, but I've never read anything that touches on why:

http://php.net/manual/en/language.oop5. autoload.php :

注意:如果在CLI交互模式下使用PHP,则无法自动加载.

有人知道在CLI模式下工作时阻止PHP作为一种语言自动加载的原因吗?

Does anyone know what is preventing PHP, as a language, from autoloading while working in CLI mode?

推荐答案

在命令行上自动加载有效.请注意提到交互式".

Autoloading on the command line works. Do note the mention of "interactive".

PHP带有两种交互模式,但是不幸的是,这两种模式都是通过在命令外壳上使用php -a来调用的.

PHP comes with two interactive modes, but unfortunately both of them are invoked by using php -a on your command shell.

如果PHP是在readline支持下编译的,则将获得交互式shell".在这种模式下,几乎可以立即评估每个命令,并且您还可以获得有关任何分析错误的即时反馈.

If PHP is compiled with readline support, you get the "interactive shell". In this mode, every command is evaluated nearly instantly, and you also get instant feedback about any parsing errors.

在此模式下,自动加载有效.

In this mode, autoloading works.

另一种模式称为交互模式".此模式没有任何花哨的东西,它只发出一条短消息,然后您基本上编写了一个PHP脚本-除非关闭STDIN,否则什么都不会做.只有这样,编写的代码才会被解析并执行.这是唯一不为未知类调用__autoload()函数的情况.

The other mode is called "interactive mode". This mode is void of any fancy stuff, it only emits a short message, and then you basically write a PHP script - and nothing gets done unless you close the STDIN. Only then the written code gets parsed and executed. And this is the only case where the __autoload() function is not called for unknown classes.

交互式shell会话示例(在Linux上使用PHP 5.3.2):

Example for an interactive shell session (using PHP 5.3.2 on Linux):

vagrant@lucid32:/etc/apache2$ php -a
Interactive shell

php > function __autoload($classname) {
php { echo "Autoload $classname";
php { eval("class $classname{}");
php { return true;
php { }
php > new Bar();
Autoload ▒▒Bar
php > new FooBar();
Autoload ▒▒FooBar
php > var_dump($a = get_declared_classes());
array(123) {
[0]=>
string(8) "stdClass"
[1]=>
string(9) "Exception"
[2]=>
string(14) "ErrorException"
   ... lots of internal classes here ...
[121]=>
string(3) "Bar"
[122]=>
string(6) "FooBar"
}
php >

交互模式示例(在Windows上使用PHP 5.3.18)

Example for an interactive mode (using PHP 5.3.18 on Windows)

PS C:\Users\sven> php -a
Interactive mode enabled

<?php
function __autoload($class) { echo "Auto: $class"; eval("class $class {}"); }
echo "Hello World";
$x = new Foo;
var_dump($x);
var_dump($a = get_declared_classes());
^Z
Hello World
Fatal error: Class 'Foo' not found in - on line 4

Call Stack:
  100.6337    1114608   1. {main}() -:0

这篇关于为什么PHP的自动加载功能无法在CLI模式下工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆