使我的函数可以访问外部变量


76

我外面有一个数组:

$myArr = array();

我想让我的函数可以访问其外部的数组,以便可以向其添加值

function someFuntion(){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

如何为函数赋予正确的作用域范围?

Answers:


127

默认情况下,当您在函数内部时,您无权访问外部变量。


如果您希望函数可以访问外部变量,则必须global在函数内部将其声明为:

function someFuntion(){
    global $myArr;
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

有关更多信息,请参见可变作用域

但是请注意,使用全局变量不是一个好习惯:通过这种方法,您的函数不再独立。


一个更好的主意是使您的函数返回结果

function someFuntion(){
    $myArr = array();       // At first, you have an empty array
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
    return $myArr;
}

并像这样调用函数:

$result = someFunction();


您的函数也可以使用参数,甚至可以处理通过引用传递的参数

function someFuntion(array & $myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
}

然后,像这样调用函数:

$myArr = array( ... );
someFunction($myArr);  // The function will receive $myArr, and modify it

有了这个 :

  • 您的函数收到了外部数组作为参数
  • 并且可以对其进行修改,因为它已通过引用传递。
  • 比使用全局变量更好的做法是:函数是一个单元,独立于任何外部代码。


有关此的更多信息,您应该阅读PHP手册的Functions部分,尤其是以下小节:


3
@Machine:一个很好的问题^^ (自那以后,我编辑了我的答案几次,以添加更多信息;也许是因为一开始不够完整,所以被否决了……它可能与global有关,人们不喜欢的...)
Pascal MARTIN 2010年

3
@Machine Anti-Global先生@Coronatus认为完全可行的答案是错误的。他的1,662个代表使他正确了……
泰勒·卡特

1
我读了您的初始版本,它仍然足以进行+1票表决,绝对不值得投下反对票。
PatrikAkerstrand 2010年

global方法引用全局变量,而不是外部变量!
尤金·马拉

26
$foo = 42;
$bar = function($x = 0) use ($foo){
    return $x + $foo;
};
var_dump($bar(10)); // int(52)

更新:现在支持箭头功能,但我会让更多使用它的人来创建答案


11
Global $myArr;
$myArr = array();

function someFuntion(){
    global $myArr;

    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

请注意,由于它有一些缺点,因此一般人会远离全球。

你可以试试这个

function someFuntion($myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
    return $myArr;
}
$myArr = someFunction($myArr);

这样就可以做到,因此您不必依赖Globals。


函数范围内的全局变量是足够的,您是否有意向“主”范围添加了一个全局变量?好的做法?(从不使用全局变量。)
斯文斯(Svens

该函数外部的“全局”是无用的,除非整个文件是从另一个函数包含的。
andreszs 2014年

9
$myArr = array();

function someFuntion(array $myArr) {
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;

    return $myArr;
}

$myArr = someFunction($myArr);

1
如果片段中有解释,此答案的质量将大大提高。
mickmackusa

3

使用全局变量是一种可能不太理想的实现目标的方法。

您可以通过添加global $myArr;到函数的开头来实现。但是请注意,在大多数情况下,使用全局变量是一个坏主意,并且可以避免。

更好的方法是将数组作为参数传递给函数:

function someFuntion($arr){
    $myVal = //some processing here to determine value of $myVal
    $arr[] = $myVal;
    return $arr;
}

$myArr = someFunction($myArr);

0

两个答案

1.回答问题。

2.简单的更改等于更好的方法!

答案1-将Vars数组传递给类中的__construct(),也可以将构造保留为空,然后将Arrays传递给函数。

<?php

// Create an Array with all needed Sub Arrays Example: 
// Example Sub Array 1
$content_arrays["modals"]= array();
// Example Sub Array 2
$content_arrays["js_custom"] = array();

// Create a Class
class Array_Pushing_Example_1 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Primary Contents Array as Parameter in __construct
    public function __construct($content_arrays){

        // Declare it
        $this->content_arrays = $content_arrays;

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class with the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_1($content_arrays);

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

答案2-然而,简单的更改将使其与现代标准保持一致。只需在类中声明您的数组即可。

<?php

// Create a Class
class Array_Pushing_Example_2 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Declare Contents Array and Sub Arrays in __construct
    public function __construct(){

        // Declare them
        $this->content_arrays["modals"] = array();
        $this->content_arrays["js_custom"] = array();

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class without the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_2();

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

这两个选项都输出相同的信息,并允许函数将Array和子Array的信息推入并检索到代码中的任何位置(鉴于已先推入数据)。第二个选项提供了对如何使用和保护数据的更多控制。它们可以按您的需求进行修改,但是如果用于扩展Controller,它们可以在Controller正在使用的任何类之间共享其值。两种方法都不需要使用Global。

输出:

数组自定义内容结果

模数-数量:5

一种

b

C

OO

JS自定义-计数:9

1个

2B与否2B

3

42

5

汽车

自行车

玻璃


有太多无关的代码,很难在这里看到您提出的解决方案。
robrecord
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.