[英]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.