[英]php variable scope in functions?
如何訪問另一個函數中定義的函數中的變量?
例如:
<?php
function a() {
$fruit = "apple";
function b(){
$country="USA";
// How can I here access to $fruit
}
// And how can I here access to $country
}
?>
您正在執行的操作非常糟糕,因為無法以這種方式像JavaScript一樣嵌套PHP的函數。 在您的例子a
和b
都只有全局函數,如果你嘗試調用你會得到一個錯誤a
兩次。
我懷疑您想要的是這種語法:
function a() {
$fruit = "apple";
$country = null;
$b = function() use ($fruit, &$country) {
$country="USA";
// How can I here access to $fruit
};
// And how can I here access to $country
}
當然,您需要在$b()
內調用$b()
$a()
。
您可以使用全局詞。 試試看,告訴我是否可行。
<?php
function a() {
$fruit = "apple";
$country=b();
// And how can I here access to $country
}
function b(){
global $fruit;
$country="USA";
// How can I here access to $fruit
return $country;
}
?>
,但是你應該那樣做
<?php
function a() {
$fruit = "apple";
$country=b($fruit);
// And how can I here access to $country
}
function b($fruit){
$country="USA";
// How can I here access to $fruit
return $country;
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.