PHP速记概述 [英] Overview of PHP shorthand

查看:79
本文介绍了PHP速记概述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP进行编程已经有很多年了,但是我从未学习过如何使用任何速记.我不时在代码中遇到它,并且很难阅读它,所以我想学习该语言存在的另一种速记,以便我可以阅读它并开始使用它来节省时间/行数,但是我似乎找不到所有速记的全面概述.

I've been programming in PHP for years now, but I've never learned how to use any shorthand. I come across it from time to time in code and have a hard time reading it, so I'd like to learn the different shorthand that exists for the language so that I can read it and start saving time/lines by using it, but I can't seem to find a comprehensive overview of all of the shorthand.

Google搜索几乎专门显示了if/else语句的简写,但我知道不仅限于此.

A Google search pretty much exclusively shows the shorthand for if/else statements, but I know there must be more than just that.

我是用速记的方式谈论诸如此类的事情:

By shorthand, I am talking about stuff like:

($var) ? true : false;

推荐答案

以下是PHP中使用的一些速记运算符.

Here are some of the shorthand operators used in PHP.

//If $y > 10, $x will say 'foo', else it'll say 'bar'
$x = ($y > 10) ? 'foo' : 'bar';

//Short way of saying <? print $foo;?>, useful in HTML templates
<?=$foo?>

//Shorthand way of doing the for loop, useful in html templates
for ($x=1; $x < 100; $x++):
   //Do something
end for;

//Shorthand way of the foreach loop
foreach ($array as $key=>$value):
   //Do something;
endforeach;

//Another way of If/else:
if ($x > 10):
    doX();
    doY();
    doZ();
else:
    doA();
    doB();
endif;

//You can also do an if statement without any brackets or colons if you only need to
//execute one statement after your if:

if ($x = 100)
   doX();
$x = 1000;

// PHP 5.4 introduced an array shorthand

$a = [1, 2, 3, 4];
$b = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];

这篇关于PHP速记概述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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