在函数中使用变量,该变量未在函数外部定义


Using a variable in a function, which isn't defined outside the function

我收到一个错误:

注意:未定义的变量:价格

使用此代码:

<?php
$price[1] = 100;
$store[1] = "apple";
function check ($m) {
  if ($m == "apple") {
    $z = $price[1];
  }
  return $z;
}

?>
<?= check( $store[1] ) ?>

它没有使$z等于price[1],而是试图将其设置为不存在的price

如何正确定义它?

$price

函数范围内未定义。如果您需要函数访问该变量,有几种方法可以做到这一点。最直接的方法是将$price作为另一个参数添加到函数中。

function check ($m, $price) { ...

然后在调用check()时使用$price数组作为第二个参数:

<?= check( $store[1], $price) ?>

请记住,函数内部的$price不是函数外部存在的变量,而是函数的副本。

您可以在 PHP 文档中了解有关变量作用域的更多信息 此处.最好避免使用global,除非出于某种原因完全有必要。在这种情况下,它应该是没有必要的。

您正在询问一个特定问题 - 这很容易解决 - 但实际上您正在尝试完成其他比您提供的代码示例更容易解决的事情。

考虑到你的代码,加上一些关于你可能要去哪里的"假设",我会推荐一些更像这样的东西:

$price[1] = 100;
$price[2] = 150;
$price[5] = 225;
$store[1] = "apple";
$store[2] = "orange";
$store[5] = "kiwi";
// Option 1: Global in the variables.  Nothing wrong with it here...
function check ( $m ) {
   global $price, $store;
   $index = array_search( $m, $store );
   return ( isset( $price[ $index ] ) ) ? $price[ $index ] : 0;
}
// usage:
echo check( $store[1] );

// Option 2: Pass in all the variables you need
function check ( $m, $price, $store ) {
   $index = array_search( $m, $store );
   return ( isset( $price[ $index ] ) ) ? $price[ $index ] : 0;    
}
// usage:
echo check( $store[1], $price, $store );

// Option 3: Since you seem to know the index already, just pass THAT in
function check ( $index, $price, $store ) {
   return ( isset( $price[ $index ] ) ) ? $price[ $index ] : 0;    
}
// usage:
echo check( 1, $price, $store );

// Option 4: Globals, plus since you seem to know the index already, just pass THAT in
function check ( $index ) {
   global $store, $price;
   return ( isset( $price[ $index ] ) ) ? $price[ $index ] : 0;    
}

// usage:
echo check( 1 );

变量不是在函数内部定义的,您需要将函数内所需的所有变量作为参数传递,例如:

$price[1] = 100;
$store[1] = "apple";
function check ($m, $price) {
  if ($m == "apple") {
    $z = $price[1];
  }
  return $z;
}
//use the function
check( $store[1], $price )

试试这个:

function check ($m) {
  global $price;
  (...)