こちらの記事をたまたま見て気になったので投稿。
PHPでforeachなどを使う時の注意点。ブロックスコープのお話。
確かにループで一時的に必要な変数にスコープが無いと都合が悪いのはその通りなんだけど、解決策にモヤモヤ…
スコープが欲しいところに無いなら作ればいいわけで
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$fruits = array('banana', 'melon', 'orange'); | |
function joinFruits($fruits) { | |
$result = ''; | |
foreach ($fruits as $fruit) { | |
$result .= $fruit; | |
} | |
return $result; | |
} | |
$fruits_str = joinFruits($fruits); | |
var_dump($fruit); // => undefined variable error | |
var_dump($fruits_str); // => bananamelonorange |
関数に入れればスコープが作れる。
もっと言えばクラスにすればいいと思う。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fruits { | |
var $_data; | |
public function __construct($data) { | |
$this->_data = $data; | |
} | |
public function join() { | |
$result = ''; | |
foreach ($this->_data as $datum) { | |
$result .= $datum; | |
} | |
return $result; | |
} | |
} | |
$fruits = new Fruits(array('banana', 'melon', 'orange')); | |
var_dump($fruits->join()); // => bananamelonorange |
このコメントはブログの管理者によって削除されました。
返信削除