Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

php编码的一些小规范 #104

Open
zhangyachen opened this issue Dec 22, 2016 · 1 comment
Open

php编码的一些小规范 #104

zhangyachen opened this issue Dec 22, 2016 · 1 comment
Labels

Comments

@zhangyachen
Copy link
Owner

zhangyachen commented Dec 22, 2016

最近在整理线上的hhvm warning,虽然每天产生百万级别的warning,但是归结起来只有几类warning。这几类warning虽然都是很小的编码细节导致的,但是也记下来供自己之后编码注意。

Invalid argument supplied for foreach()

foreach($a as $val){
    //do something
}

foreach是再常见不过的用法,但是当$a不是数组时,就会报出warning,这点占总warning的60%以上:

Warning: Invalid argument supplied for foreach() in /home/work/orp/zyc/a.php on line 7

规范的做法是在foreach前判断$a的类型:

$a = is_array($a) ? $a : array();
foreach($a as $val){
    //do something
}

Invalid operand type was used: array_merge expects array(s)

当$a,$b不是数组时,就会报出上述的错误。
规范的做法是array_merge前判断$a与$b的类型。

$a = is_array($a) ? $a : array();
$b = is_array($b) ? $b : array();
$c = array_merge($a,$b);

in_array() expects parameter 2 to be an array or collection

in_array($ele,$array);

当$array不是数组时,就会报上述错误,解决办法同上。

function expects exactly 2 parameters, 1 given

假设现在有个公共文件common.php,里面定义了一个类和函数:

class Common{
    function common($a){
        //do something
    }
}

现在有个文件调用了common.php里的common函数:

//a.php
$obj = new Common();
$ret = $obj->common(5);

这时,有人修改了common.php,将函数参数多加了一个$b:

class Common{
    //add param $b by xxx
    function common($a,$b){
        //do something
    }
}

但是此时作者并不知道有个a.php也调用了这个方法,此时就会报错:

common() expects exactly 2 parameters, 1 given

推荐的修复方案时,之后加函数参数时可以为添加的参数多加一个默认值即可:

class Common{
    //add param $b by xxx
    function common($a,$b=0){
        //do something
    }
}
@mingyun
Copy link

mingyun commented Feb 12, 2017

学习了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants