복붙노트

내 함수에 외부 변수 액세스 권한 부여

PHP

내 함수에 외부 변수 액세스 권한 부여

외부에 배열이 있습니다.

$myArr = array();

외부에 배열에 함수 액세스 권한을 부여하여 값을 추가 할 수 있습니다.

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

변수에 올바른 범위를 지정하려면 어떻게해야합니까?

해결법

  1. ==============================

    1.기본적으로 함수 안에 있으면 외부 변수에 액세스 할 수 없습니다.

    기본적으로 함수 안에 있으면 외부 변수에 액세스 할 수 없습니다.

    함수가 외부 변수에 액세스 할 수있게하려면 함수 내에 전역 변수로 선언해야합니다.

    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 섹션을 참조하십시오. 특히 다음 하위 섹션을 읽어야합니다.

  2. ==============================

    2.

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

    3.

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

    4.

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

    그렇게하면 지구본에 의존하지 않게 될 것입니다.

  5. ==============================

    5.목표 달성을위한 좋은 방법은 글로벌 변수를 사용하는 것입니다.

    목표 달성을위한 좋은 방법은 글로벌 변수를 사용하는 것입니다.

    전역 $ myArr을 추가하여이를 달성 할 수 있습니다. 당신의 기능의 시작에. 그러나 전역 변수를 사용하는 것은 대부분의 경우 나쁜 생각이며 피할 수없는 경우가 있습니다.

    훨씬 더 좋은 방법은 배열을 함수의 인수로 전달하는 것입니다.

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

    6.두 가지 대답

    두 가지 대답

    1. 질문 된 질문에 대답하십시오.

    2. 간단한 변화가 더 나은 방법입니다!

    Answer 1 - Vars Array를 클래스의 __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>";
    
    ?>
    

    두 옵션 모두 동일한 정보를 출력하고 배열 및 하위 배열에서 정보를 코드의 임의의 위치로 밀어 넣고 가져올 수 있습니다 (데이터가 먼저 푸시 된 경우). 두 번째 옵션은 데이터 사용 및 보호 방식을보다 효율적으로 제어합니다. 필요에 따라 변경하여 사용할 수 있지만 컨트롤러를 확장하는 데 사용 된 경우 컨트롤러가 사용하는 모든 클래스간에 값을 공유 할 수 있습니다. 어느 방법도 전역 (들)의 사용을 필요로하지 않습니다.

    산출:

    배열 사용자 정의 컨텐츠 결과

    Modals - 개수 : 5

    에이

    기음

    FOO

    JS 사용자 - 개수 : 9

    1

    2B인지 2B인지의 여부

    3

    42

    5

    자전거

    유리

  7. from https://stackoverflow.com/questions/2531221/giving-my-function-access-to-outside-variable by cc-by-sa and MIT license