[英]PHP: what does a double assignment look like in longform?
我甚至不确定如何谷歌这个。 如何将这个PHP语句写成longform?
$recentlyViewed = $products = $this->getRecentlyViewedProducts();
这样的优化让专家感觉很聪明,初学者觉得非常愚蠢。 我很确定我明白结果是什么,但也许我错了。
$products = $this->getRecentlyViewedProducts();
$recentlyViewed = ($products) ? true : false;
$products = $this->getRecentlyViewedProducts();
$recentlyViewed = $products;
通过Twitter,似乎B是等价的。
写出明显简单的代码。 别聪明。
$recentlyViewed = $products = $this->getRecentlyViewedProducts();
和
$products = $this->getRecentlyViewedProducts();
$recentlyViewed = ($products) ? true : false;
我认为这是等价的:
不,它不相同。
让我们看看差异
$recentlyViewed = $products = range(1,10);
所以如果你print_r
那么值就是
print_r($recentlyViewed);
print_r($products);
这将从[1,2,3,....10]
打印两个阵列但是
$products = range(1,10);
$recentlyViewed = ($products) ? true : false;
因此,如果您打印$products
和$recentlyViewed
recentViewed,那么结果将是第一个打印array
,另一个将打印1
。
所以什么相当于
$recentlyViewed = $products = $this->getRecentlyViewedProducts();
将会
$products = $this->getRecentlyViewedProducts();
$recentlyViewed = $products;
相当于此
$products = $this->getRecent();
$recentlyViewed = $products;
我不确定对于$products
的测试是如何有意义的,因为双重赋值不会返回布尔值。
在这里看到原始类型和对象之间的区别。
多个变量赋值是通过值还是引用完成的?
当你写:
$recentlyViewed = $products = $this->getRecentlyViewedProducts();
PHP所做的是从右手乞求并将最正确的值分配给左侧变量(如果有的话)。 此值可以是const值(即字符串或数字),函数的另一个变量或返回值$this->getRecentlyViewedProducts()
在本例中$this->getRecentlyViewedProducts()
)。 所以这是步骤:
(
$这个- > getRecentlyViewedProducts() in this case)
$products
$product
分配给$recentlyViewed
因此,如果我们假设您的getRecentlyViewedProducts
函数返回'Hello Brendan!',则在执行结束时, $products
和$recentlyViewed
将具有相同的值。
在PHP中,变量类型是隐式的,因此您可以在if
语句中直接使用它们:
if($recentlyViewed) { ... }
在这种情况下,如果$recentlyViewed
是设置好的,它的值$recentlyViewed
是什么,其他是0
, false
或null
,你if
条件将满足。
在PHP中使用非布尔值作为检查条件是很常见的,无论如何,如果你使用$recentlyViewed
作为标志,为了代码可读性和内存优化,最好这样做(注意如果你的函数返回例如一个大字符串,将其值复制到一个单独的变量中,将其用作标志不是明智的选择):
$recentlyViewed = $products ? true : false;
要么
$recentlyViewed = $products ? 1 : 0;
althogh结果不会有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.