我想直接用命令行执行一条PHP语句,比如if(function_exists("my_func")) echo 'function exists';,而不必使用单独的PHP文件.

这怎么可能呢?

推荐答案

If you're going to do PHP in the command line, I recommend you install 100.这更有趣.

无论如何,php命令提供two switches to execute code from the command line:

-r <code>        Run PHP <code> without using script tags <?..?>
-R <code>        Run PHP <code> for every input line

你可以这样使用php's -r switch:

php -r 'echo function_exists("foo") ? "yes" : "no";'

上面的PHP命令应该是output noreturns 0,如您所见:

>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0

另一个有趣的switch 是php -a:

-a               Run as interactive shell

它是sort of lame compared to 100,但如果你不想安装the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on,那么use -a as such:

>>> php -a
Interactive shell

php > echo function_exists("foo") ? "yes" : "no";
no
php >

If it doesn't work在你的盒子上,就像我的盒子es(testedUbuntuArch Linux上),然后是probably your PHP setup is fuzzy or broken.如果运行此命令:

php -i | grep 'API'

你看:

Server API => Command Line Interface

If you don't,这意味着maybe another command will provides the CLI SAPI.试试php cli;也许它是你的操作系统中可用的一个包或命令.

If you do确保您的php命令使用CLI(命令行界面)SAPI(服务器API),然后运行php -h | grep codefind out which crazy switch - as this hasn't changed for year-允许在您的版本/设置中运行代码.

另外两个例子,只是为了确保它在我的盒子上工作:

>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes

另外,请注意,扩展可能是在CLI中加载的,而不是在CGI或Apache SAPI中加载的.It is likely that several PHP SAPIs use different php.ini files,例如,Gentoo Linux盒上的/etc/php/cli/php.ini/etc/php/cgi/php.ini/etc/php/apache/php.ini.找出哪个ini文件与php -i | grep ini一起使用.

Php相关问答推荐

我的docker—compose lamp stack在软件更新后不工作:Containerconfig错误'''

邮箱打开跟踪器不工作时发送邮件使用laravel调度程序

无法在Laravel/Vue停靠容器中启动MySQL

Laravel;Composer安装突然返回选项快捷方式不能为空.

SendGrid响应PHP

如何保存基于用户 Select 的复选框 Select 模式

列出所有WooCommerce处理订单中的产品数量,SKU和品牌

SFTP在PHP(phpseclib3\Net\SFTP)-过滤目录列表结果服务器端可能吗?类似于psftp中的LS命令?

从WooCommerce管理订单汇总中隐藏原始小计行

隐藏WooCommerce管理子菜单;主页;来自store 经理

在 WooCommerce 更新结帐事件上动态更新自定义内容

如何在 PHP 中以 hh:mm:ss 格式获取两个 strtotime datetime/s 之间的时间差

WooCommerce:如果购物车中已存在产品,则增加购物车商品数量

在php中计算两个没有假期的日期之间的小时差

无法读取某些 WordPress 主机上的 cookie

将 WooCommerce 0 销售价格替换为自定义文本,并保留常规价格删除线

在 WooCommerce wc_get_products 函数中处理自定义分类法

添加或删除优惠券后自动刷新 WooCommerce checkout 表单字段

Laravel的Storage::exists返回false,而file_exists返回true.

为什么可以从 PHP 类访问 PHP Trait 的私有成员?