簡體   English   中英

PHP:longform中的雙重賦值是什么樣的?

[英]PHP: what does a double assignment look like in longform?

我甚至不確定如何谷歌這個。 如何將這個PHP語句寫成longform?

$recentlyViewed = $products = $this->getRecentlyViewedProducts();

這樣的優化讓專家感覺很聰明,初學者覺得非常愚蠢。 我很確定我明白結果是什么,但也許我錯了。

A:這相當嗎?

$products = $this->getRecentlyViewedProducts();
$recentlyViewed = ($products) ? true : false;

B:這相當嗎?

$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是什么,其他是0falsenull ,你if條件將滿足。
在PHP中使用非布爾值作為檢查條件是很常見的,無論如何,如果你使用$recentlyViewed作為標志,為了代碼可讀性和內存優化,最好這樣做(注意如果你的函數返回例如一個大字符串,將其值復制到一個單獨的變量中,將其用作標志不是明智的選擇):

$recentlyViewed = $products ? true : false;

要么

$recentlyViewed = $products ? 1 : 0;

althogh結果不會有所不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM