Предоставление моей функции доступа к внешней переменной
У меня есть массив снаружи:
$myArr = array();
Я хотел бы дать моей функции доступ к массиву вне его, чтобы он мог добавлять значения к нему
function someFuntion(){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
Как дать функции правильную область видимости для переменной?
6 ответов
По умолчанию, когда вы находитесь внутри функции, у вас нет доступа к внешним переменным.
Если вы хотите, чтобы ваша функция имела доступ к внешней переменной, вы должны объявить ее как 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 и, в особенности, следующие подразделы:
$foo = 42;
$bar = function($x = 0) use ($foo){
return $x + $foo;
};
var_dump($bar(10)); // int(52)
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);
Это сделало бы так, чтобы вы не полагались на глобалы.
$myArr = array();
function someFuntion(array $myArr) {
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
Один и, вероятно, не очень хороший способ достижения вашей цели - использование глобальных переменных.
Вы можете достичь этого, добавив global $myArr;
к началу вашей функции. Однако обратите внимание, что использование глобальных переменных в большинстве случаев является плохой идеей и, вероятно, ее можно избежать.
Гораздо лучше было бы передать ваш массив в качестве аргумента вашей функции:
function someFuntion($arr){
$myVal = //some processing here to determine value of $myVal
$arr[] = $myVal;
return $arr;
}
$myArr = someFunction($myArr);
Два ответа
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>";
?>
Обе опции выводят одну и ту же информацию и позволяют функции выдвигать и извлекать информацию из массива и вложенных массивов в любое место кода (учитывая, что данные были переданы первыми). Второй вариант дает больше контроля над тем, как данные используются и защищены. Они могут использоваться как просто изменяющие ваши потребности, но если они использовались для расширения Контроллера, они могли бы делиться своими значениями с любым из Классов, которые использует Контроллер. Ни один из методов не требует использования Global(s).
Выход:
Array Custom Content Results
Модалы - Количество: 5
б
с
FOO
Foo
JS Custom - Количество: 9
1
2B или нет 2B
3
42
5
автомобиль
жилой дом
велосипед
стакан