【相干学习保举:php图文教程】
这5个PHP编程中的没有良习气,肯定要改掉 PHP世界上最佳的言语!
测试轮回前数组能否为空?
$items = [];// ...if (count($items) > 0) { foreach ($items as $item) { // process on $item ... }}复制代码
foreach
轮回或数组函数(array_*)
能够解决空数组。
- 没有需求进步前辈行测试
- 能够缩小一层缩进
$items = [];// ...foreach ($items as $item) { // process on $item ...}复制代码
将办法的一切内容封装正在if语句中
function foo(User $user) { if (!$user->isDisafunction foo(User $user) { if (!$user->isDisabled()) { // ... // long process // ... } }bled()) { // ... // long process // ... } }复制代码
这没有是特定于PHP的,但我常常看到它。你能够经过提前前往,来缩小缩进级此外极简代码! 该函数的一切“有用”主表现正在处于第一个缩进级别
function foo(User $user) { if ($user->isDisabled()) { return; } // ... // long process // ...}复制代码
屡次挪用isset
办法
$a = null; $b = null; $c = null;// ...if (!isset($a) || !isset($b) || !isset($c)) { throw new Exception("undefined variable"); }// orif (isset($a) && isset($b) && isset($c) { // process with $a, $b et $c}// or $items = [];//...if (isset($items['user']) && isset($items['user']['id']) { // process with $items['user']['id']}复制代码
咱们常常需求反省能否已界说变量(而没有是null
)。
正在PHP中,咱们能够应用isset函数来做到这一点。并且该函数一次能够承受多个参数!
$a = null; $b = null; $c = null;// ...if (!isset($a, $b, $c)) { throw new Exception("undefined variable"); }// orif (isset($a, $b, $c)) { // process with $a, $b et $c}// or $items = [];//...if (isset($items['user'], $items['user']['id'])) { // process with $items['user']['id']}复制代码
echo
办法以及sprintf
连系应用
$name = "John Doe";echo sprintf('Bonjour %s', $name);复制代码
这段代码可能正在浅笑,然而我可巧写了一段工夫。并且我依然看到不少!除了了却合echo
以及sprintf
,咱们能够简略地应用printf
办法。
$name = "John Doe"; printf('Bonjour %s', $name);复制代码
经过组合两种办法反省数组中键的存正在
$items = [ 'one_key' => 'John', 'search_key' => 'Jane', ];if (in_array('search_key', array_keys($items))) { // process}复制代码
最初一个谬误我看到的往往是联结应用in_array
以及array_keys
。一切这些均可以应用array_key_exists交换。
$items = [ 'one_key' => 'John', 'search_key' => 'Jane', ];if (array_key_exists('search_key', $items)) { // process}复制代码
咱们还能够应用isset来反省值能否是null。
if (isset($items['search_key'])) { // process}复制代码
感激您的浏览,假如对您有协助,欢送存眷"CRMEB"掘金号。码云上有咱们开源的商城名目,常识付费名目,均是基于PHP开发,学习钻研欢送应用,存眷咱们放弃联络!
相干学习保举:php编程(视频)
以上就是肯定要改掉 这5个PHP编程中的没有良习气!的具体内容,更多请存眷资源魔其它相干文章!
标签: php php开发教程 php开发资料 php开发自学
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!