2012年10月29日星期一

PHP Notes

exec()


  1. 获得命令执行结果,命令和参数完后加上 2>&1
    [bash]
    $output = array();
    $lastLine = exec("php -l test.php 2>&1", $output);
    [/bash]

  2. 立即退出,而不是等命令执行完后再退出
    [bash]
    exec("php -l test.php > /dev/null &");
    [/bash]



php_sapi_name()

返回 小写的 PHP 使用的 interface。如从命令行执行时返回 cli


Deprecated: Assigning the return value of new by reference is deprecated in ...

运行旧时代码,收到错误:
[php gutter="false"]
Deprecated: Assigning the return value of new by reference is deprecated in .. line
[/php]
Google ,原来是 PHP 升级引发的问题。PHP 从 5.3 起,废除了 =& 符号,用 = 就等于是直接引用。详细如下:

  1. PHP5 对象复制是采用引用的方式

  2. 如果不采用引用方式,则需要在复制对象时加关键字 clone

  3. 如果在复制的过程中,同时要变更某些属性,则增加函数 _clone()



Problem: Fatal error: Call to undefined function: pcntl_fork() in ...

编译 PHP 有加上参数 --enable-pcntl,且安装成功后,在 PHP 信息中,能看到 PHP 支持 pcntl 的信息:
[bash]
[root@www ~]# php -i | grep pcntl
Configure Command => './configure' '--prefix=/usr/local/php' '--with-freetype-dir' '--with-jpeg-dir' '--with-png-dir' '--with-curl' '--with-gd' '--with-iconv' '--with-mcrypt' '--with-mhash' '--with-mysql=mysqlnd' '--with-mysqli=mysqlnd' '--with-openssl' '--with-pdo-mysql=mysqlnd' '--with-gettext' '--with-zlib' '--enable-bcmath' '--enable-ftp' '--enable-fpm' '--with-fpm-user=www' '--with-fpm-group=www' '--enable-gd-native-ttf' '--enable-mbstring' '--enable-pcntl' '--enable-pdo' '--enable-sockets' '--enable-sqlite-utf8' '--enable-shmop' '--enable-zip' '--disable-ipv6' '--disable-debug' '--without-pear'
pcntl
pcntl support => enabled
[/bash]

在浏览器中访问有调用 pcntl_fork()的脚本时,收到下面的错误提示,但在命令行执行该脚本时正常运行:
[bash]
Problem: Fatal error: Call to undefined function: pcntl_fork() in ...
[/bash]

PHP 官方网站在 介绍 pcntl 时有提到:
Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

即调用 pcntl_xxx 系列函数的脚本,不能在浏览器或是任何 web 方式的环境下访问。


Strict Standards: Only variables should be passed by reference

[php]
<?php
$string = 'test1 test2 test3 test4';
$array = array_shift(explode(' ', $string));

print_r($array);
?>
[/php]
执行上面代码,收到错误:
[bash gutter="false"]
[root@www tmp]# php test.php
PHP Strict Standards: Only variables should be passed by reference in /tmp/test.php on line 3

Strict Standards: Only variables should be passed by reference in /tmp/test.php on line 3
[/bash]
之所以报这错误,因为 array_shift 的参数是引用传递的,PHP 5.3+ 默认只能传递具体的变量,而不能直接是传递函数返回值。代码修改成:
[php]
<?php
$string = 'test1 test2 test3 test4';
$array = explode(' ', $string);
$value1 = array_shift($array);

print_r($value1);
?>
[/php]
另外,当程序设置的报错模式为严格模式时也会收到上面的错误:
[php]
error_reporting (E_ALL | E_STRICT);
[/php]

Resources:

没有评论 :

发表评论