Подтвердить что ты не робот

Предоставление моей функции доступа к внешней переменной

У меня есть массив снаружи:

$myArr = array();

Я хотел бы предоставить доступ моей функции к массиву вне его, чтобы он мог добавлять к нему значения

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

Как присвоить функции правильную область видимости переменной?

4b9b3361

Ответ 1

По умолчанию, когда вы находитесь внутри функции, у вас нет доступа к внешним переменным.


Если вы хотите, чтобы ваша функция имела доступ к внешней переменной, вы должны объявить ее как 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 и, особенно, следующее подразделы:

Ответ 2

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

ОБНОВЛЕНИЕ: теперь есть поддержка функций стрелок, но я позволю кому-то, кто использовал это больше, чтобы создать ответ

Ответ 3

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.

Ответ 4

$myArr = array();

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

    return $myArr;
}

$myArr = someFunction($myArr);

Ответ 5

Один и, вероятно, не очень хороший способ достижения вашей цели будет использовать глобальные переменные.

Это можно сделать, добавив global $myArr; в начало вашей функции. Однако обратите внимание, что использование глобальных переменных в большинстве случаев является плохой идеей и, вероятно, можно избежать.

Лучше всего передать массив в качестве аргумента вашей функции:

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

$myArr = someFunction($myArr);

Ответ 6

Два ответа

1. Ответьте на заданный вопрос.

2. Простое изменение - лучший способ!

Ответ 1. Передайте массив Vars в __construct() в классе, вы также можете оставить конструкцию пустой и передать массивы через ваши функции.

<?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

Модалы - количество: 5

а

б

с

FOO

Foo

JS Custom - количество: 9

1

2B или не 2B

3

42

5

автомобиль

дом

велосипед

стекло