Giving my function access to outside variable

2019-01-01 01:02发布

问题:

I have an array outside:

$myArr = array();

I would like to give my function access to the array outside it so it can add values to it

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

How do I give the function the right scoping to the variable?

回答1:

By default, when you are inside a function, you do not have access to the outer variables.


If you want your function to have access to an outer variable, you have to declare it as global, inside the function :

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

For more informations, see Variable scope.

But note that using global variables is not a good practice : with this, your function is not independant anymore.


A better idea would be to make your function return the result :

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;
}

And call the function like this :

$result = someFunction();


Your function could also take parameters, and even work on a parameter passed by reference :

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

Then, call the function like this :

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

With this :

  • Your function received the external array as a parameter
  • And can modify it, as it\'s passed by reference.
  • And it\'s better practice than using a global variable : your function is a unit, independant of any external code.


For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :

  • Functions arguments
  • Returning values


回答2:

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


回答3:

$myArr = array();

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

    return $myArr;
}

$myArr = someFunction($myArr);


回答4:

Global $myArr;
$myArr = array();

function someFuntion(){
    global $myArr;

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

Be forewarned, generally people stick away from globals as it has some downsides.

You could try this

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

That would make it so you aren\'t relying on Globals.



回答5:

The one and probably not so good way of achieving your goal would using global variables.

You could achieve that by adding global $myArr; to the beginning of your function. However note that using global variables is in most cases a bad idea and probably avoidable.

The much better way would be passing your array as an argument to your function:

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

$myArr = someFunction($myArr);


回答6:

Two Answers

1. Answer to the asked question.

2. A simple change equals a better way!

Answer 1 - Pass the Vars Array to the __construct() in a class, you could also leave the construct empty and pass the Arrays through your functions instead.

<?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>\";

?>

Answer 2 - A simple change however would put it inline with modern standards. Just declare your Arrays in the Class.

<?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>\";

?>

Both options output the same information and allow a function to push and retrieve information from an Array and sub Arrays to any place in the code(Given that the data has been pushed first). The second option gives more control over how the data is used and protected. They can be used as is just modify to your needs but if they were used to extend a Controller they could share their values among any of the Classes the Controller is using. Neither method requires the use of a Global(s).

Output:

Array Custom Content Results

Modals - Count: 5

a

b

c

FOO

foo

JS Custom - Count: 9

1

2B or not 2B

3

42

5

car

house

bike

glass