需要一些关于给定PHP代码片段的澄清吗
遇到以下PHP代码片段需要一些关于给定PHP代码片段的澄清吗,php,Php,遇到以下PHP代码片段 class SearchGoogle extends Thread { public function __construct($query) { $this->query = $query; } public function run() { $this->html = file_get_contents('http://google.fr?q='.$this->query);
class SearchGoogle extends Thread
{
public function __construct($query)
{
$this->query = $query;
}
public function run()
{
$this->html = file_get_contents('http://google.fr?q='.$this->query);
}
}
$searches = ['cats', 'dogs', 'birds'];
foreach ($searches as &$search) {
$search = new SearchGoogle($search);
$search->start();
}
我在理解下面的foreach
循环时遇到问题。在我看来是
$search
变量同时用作$searches
数组的元素和SearchGoogle
的实例。这在PHP中可能吗?PHP是松散类型的,没有什么可以阻止您重用变量:
$foo = 'Bar';
var_dump($foo);
$foo = M_PI;
var_dump($foo);
$foo = new DateTime();
var_dump($foo);
字符串(3)“条”
浮动(3.1415926535898)
对象(日期时间)#1(3){
[“日期”]=>
字符串(26)“2017-05-31 12:29:01.000000”
[“时区类型”]=>
int(3)
[“时区”]=>
字符串(13)“欧洲/马德里”
}
但在本例中,代码大致相当于:
$searches = ['cats', 'dogs', 'birds'];
foreach ($searches as $index => $search) {
$searches[$index] = new SearchGoogle($search);
$searches[$index]->start();
}
换句话说,它用
SearchGoogle
类的实例替换数组中的字符串 PHP是松散类型的,没有什么可以阻止您重用变量:
$foo = 'Bar';
var_dump($foo);
$foo = M_PI;
var_dump($foo);
$foo = new DateTime();
var_dump($foo);
字符串(3)“条”
浮动(3.1415926535898)
对象(日期时间)#1(3){
[“日期”]=>
字符串(26)“2017-05-31 12:29:01.000000”
[“时区类型”]=>
int(3)
[“时区”]=>
字符串(13)“欧洲/马德里”
}
但在本例中,代码大致相当于:
$searches = ['cats', 'dogs', 'birds'];
foreach ($searches as $index => $search) {
$searches[$index] = new SearchGoogle($search);
$searches[$index]->start();
}
换句话说,它用
SearchGoogle
类的实例替换数组中的字符串 由于它被用作引用(as&$search
,请注意符号),这意味着$search中的原始条目(例如字符串'cats'
)会被与该搜索词相关的SearchGoogle
实例覆盖。在循环之后,$searches
看起来像SearchGoogle('cats')、SearchGoogle('dogs')、SearchGoogle('birds')
,而不是'cats'、'dogs'、'birds'
。感谢您简单简洁的解释。那很酷。我怎样才能将你的帖子标记为对我有帮助的帖子呢?这是一个评论,你不能(除了投票)。我本应该把它作为答案发布,但我觉得它不符合我的标准;-)你可以只接受@lvaroGonzález的答案,因为它有相同的信息。因为它被用作引用(as&$search
,请注意符号),这意味着$search中的原始条目(例如字符串'cats'
)会被与该搜索词相关的SearchGoogle
实例覆盖。在循环之后,$searches
看起来像SearchGoogle('cats')、SearchGoogle('dogs')、SearchGoogle('birds')
,而不是'cats'、'dogs'、'birds'
。感谢您简单简洁的解释。那很酷。我怎样才能将你的帖子标记为对我有帮助的帖子呢?这是一个评论,你不能(除了投票)。我本应该把它作为答案发布,但我觉得它不符合我的标准;-)你可以接受@lvaroGonzález的答案,因为它有相同的信息。