IT박스

참조 : 변수 범위 란 무엇이며, "정의되지 않은 변수"오류의 위치 및 위치에서 액세스 할 수있는 변수는 무엇입니까?

itboxs 2020. 6. 1. 19:21
반응형

참조 : 변수 범위 란 무엇이며, "정의되지 않은 변수"오류의 위치 및 위치에서 액세스 할 수있는 변수는 무엇입니까?


참고 : 이것은 PHP에서 변수 범위를 다루기위한 참조 질문입니다. 이 패턴에 맞는 많은 질문 중 하나를이 질문의 복제본으로 닫으십시오.

PHP에서 "가변 범위"란 무엇입니까? 한 .php 파일의 변수는 다른 .php 파일에 액세스 할 수 있습니까? 때때로 "정의되지 않은 변수" 오류가 발생하는 이유는 무엇 입니까?


"가변 범위"란 무엇입니까?

변수에는 "범위"또는 "액세스 할 수있는 위치"가 제한되어 있습니다. 애플리케이션 어딘가에$foo = 'bar'; 한 번 쓴다고 해서 애플리케이션 내 다른 에서 참조 할 수있는 것은 아닙니다 . 변수 에는 유효 범위 내에서 특정 범위가 있으며 동일한 범위의 코드 만 변수에 액세스 할 수 있습니다.$foo$foo

PHP에서 범위는 어떻게 정의됩니까?

매우 간단합니다 : PHP는 함수 범위를 가지고 있습니다 . 그것은 PHP에 존재하는 유일한 종류의 범위 구분자입니다. 함수 내부의 변수는 해당 함수 내에서만 사용할 수 있습니다. 함수 외부의 변수는 함수 외부에서는 사용할 수 있지만 함수 내부에서는 사용할 수 없습니다. 이것은 PHP에 특별한 범위가 있다는 것을 의미합니다 : 글로벌 범위. 함수 외부에서 선언 된 모든 변수는이 전역 범위 내에 있습니다.

예:

<?php

$foo = 'bar';

function myFunc() {
    $baz = 42;
}

$foo글로벌 , 범위 $baz(A)에있다 지역 범위 안에 myFunc. 내부 코드 만에 myFunc액세스 할 수 $baz있습니다. 외부 코드 만에 myFunc액세스 할 수 $foo있습니다. 어느 쪽도 다른쪽에 접근 할 수 없습니다 :

<?php

$foo = 'bar';

function myFunc() {
    $baz = 42;

    echo $foo;  // doesn't work
    echo $baz;  // works
}

echo $foo;  // works
echo $baz;  // doesn't work

범위 및 포함 된 파일

파일 경계는 범위를 분리 하지 않습니다 .

a.php

<?php

$foo = 'bar';

b.php

<?php

include 'a.php';

echo $foo;  // works!

include다른 코드에 적용되는 것과 동일한 규칙이 d 코드에 적용됩니다 function. 별도의 범위 있습니다. 범위 목적을 위해 복사 및 붙여 넣기 코드와 같은 파일을 포함하는 것을 고려할 수 있습니다.

c.php

<?php

function myFunc() {
    include 'a.php';

    echo $foo;  // works
}

myFunc();

echo $foo;  // doesn't work!

위의 예에서 a.phpinside가 포함 된 경우 내부 myFunc의 모든 변수 a.php에는 로컬 함수 범위 만 있습니다. 그것들 이 전역 범위에있는 것으로 보인다고 해서 a.php반드시 그것이 의미하는 것은 아니며 실제로 코드가 포함 / 실행되는 컨텍스트에 달려 있습니다.

함수와 클래스 내부의 함수는 어떻습니까?

모든 새로운 function선언은 새로운 범위를 소개합니다. 그것은 간단합니다.

함수 내부의 (익명) 함수

function foo() {
    $foo = 'bar';

    $bar = function () {
        // no access to $foo
        $baz = 'baz';
    };

    // no access to $baz
}

클래스

$foo = 'foo';

class Bar {

    public function baz() {
        // no access to $foo
        $baz = 'baz';
    }

}

// no access to $baz

범위는 무엇입니까?

Dealing with scoping issues may seem annoying, but limited variable scope is essential to writing complex applications! If every variable you declare would be available from everywhere else inside your application, you'd be stepping all over your variables with no real way to track what changes what. There are only so many sensible names you can give to your variables, you probably want to use the variable "$name" in more than one place. If you could only have this unique variable name once in your app, you'd have to resort to really complicated naming schemes to make sure your variables are unique and that you're not changing the wrong variable from the wrong piece of code.

Observe:

function foo() {
    echo $bar;
}

If there was no scope, what would the above function do? Where does $bar come from? What state does it have? Is it even initialized? Do you have to check every time? This is not maintainable. Which brings us to...

Crossing scope boundaries

The right way: passing variables in and out

function foo($bar) {
    echo $bar;
    return 42;
}

The variable $bar is explicitly coming into this scope as function argument. Just looking at this function it's clear where the values it works with originate from. It then explicitly returns a value. The caller has the confidence to know what variables the function will work with and where its return values come from:

$baz   = 'baz';
$blarg = foo($baz);

Extending the scope of variables into anonymous functions

$foo = 'bar';

$baz = function () use ($foo) {
    echo $foo;
};

$baz();

The anonymous function explicitly includes $foo from its surrounding scope. Note that this is not the same as global scope.

The wrong way: global

As said before, the global scope is somewhat special, and functions can explicitly import variables from it:

$foo = 'bar';

function baz() {
    global $foo;
    echo $foo;
    $foo = 'baz';
}

This function uses and modifies the global variable $foo. Do not do this! (Unless you really really really really know what you're doing, and even then: don't!)

All the caller of this function sees is this:

baz(); // outputs "bar"
unset($foo);
baz(); // no output, WTF?!
baz(); // outputs "baz", WTF?!?!!

There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.

You should avoid using the global scope in any way as much as possible; most certainly you should not be "pulling" variables out of the global scope into a local scope.


Although variables defined inside of a function's scope can not be accessed from the outside that does not mean you can not use their values after that function completes. PHP has a well known static keyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind that static may also be used inside functions to define static variables.

What is it 'static variable'?

Static variable differs from ordinary variable defined in function's scope in case that it does not loose value when program execution leaves this scope. Let's consider the following example of using static variables:

function countSheep($num) {
 static $counter = 0;
 $counter += $num;
 echo "$counter sheep jumped over fence";
}

countSheep(1);
countSheep(2);
countSheep(3);

Result:

1 sheep jumped over fence
3 sheep jumped over fence
6 sheep jumped over fence

If we'd defined $counter without static then each time echoed value would be the same as $num parameter passed to the function. Using static allows to build this simple counter without additional workaround.

Static variables use-cases

  1. To store values between consequent calls to function.
  2. To store values between recursive calls when there is no way (or no purpose) to pass them as params.
  3. To cache value which is normally better to retrieve once. For example, result of reading immutable file on server.

Tricks

Static variable exists only in a local function scope. It can not be accessed outside of the function it has been defined in. So you may be sure that it will keep its value unchanged until the next call to that function.

Static variable may only be defined as a scalar or as a scalar expression (since PHP 5.6). Assigning other values to it inevitably leads to a failure at least at the moment this article was written. Nevertheless you are able to do so just on the next line of your code:

function countSheep($num) {
  static $counter = 0;
  $counter += sqrt($num);//imagine we need to take root of our sheep each time
  echo "$counter sheep jumped over fence";
}

Result:

2 sheep jumped over fence
5 sheep jumped over fence
9 sheep jumped over fence

Static function is kinda 'shared' between methods of objects of the same class. It is easy to understand by viewing the following example:

class SomeClass {
  public function foo() {
    static $x = 0;
    echo ++$x;
  }
}

$object1 = new SomeClass;
$object2 = new SomeClass;

$object1->foo(); // 1
$object2->foo(); // 2 oops, $object2 uses the same static $x as $object1
$object1->foo(); // 3 now $object1 increments $x
$object2->foo(); // 4 and now his twin brother

This only works with objects of the same class. If objects are from different classes (even extending one another) behavior of static vars will be as expected.

Is static variable the only way to keep values between calls to a function?

Another way to keep values between function calls is to use closures. Closures were introduced in PHP 5.3. In two words they allow you to limit access to some set of variables within a function scope to another anonymous function that will be the only way to access them. Being in closure variables may imitate (more or less successfully) OOP concepts like 'class constants' (if they were passed in closure by value) or 'private properties' (if passed by reference) in structured programming.

The latter actually allows to use closures instead of static variables. What to use is always up to developer to decide but it should be mentioned that static variables are definitely useful when working with recursions and deserve to be noticed by devs.


I won't post a complete answer to the question, as the existing ones and the PHP manual do a great job of explaining most of this.

But one subject that was missed was that of superglobals, including the commonly used $_POST, $_GET, $_SESSION, etc. These variables are arrays that are always available, in any scope, without a global declaration.

For example, this function will print out the name of the user running the PHP script. The variable is available to the function without any problem.

<?php
function test() {
    echo $_ENV["user"];
}

The general rule of "globals are bad" is typically amended in PHP to "globals are bad but superglobals are alright," as long as one is not misusing them. (All these variables are writable, so they could be used to avoid dependency injection if you were really terrible.)

These variables are not guaranteed to be present; an administrator can disable some or all of them using the variables_order directive in php.ini, but this is not common behaviour.


A list of current superglobals:

  • $GLOBALS - All the global variables in the current script
  • $_SERVER - Information on the server and execution environment
  • $_GET - Values passed in the query string of the URL, regardless of the HTTP method used for the request
  • $_POST - Values passed in an HTTP POST request with application/x-www-form-urlencoded or multipart/form-data MIME types
  • $_FILES - Files passed in an HTTP POST request with a multipart/form-data MIME type
  • $_COOKIE - Cookies passed with the current request
  • $_SESSION - Session variables stored internally by PHP
  • $_REQUEST - Typically a combination of $_GET and $_POST, but sometimes $_COOKIES. The content is determined by the request_order directive in php.ini.
  • $_ENV - The environment variables of the current script

참고URL : https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and

반응형