수색…


소개

변수 범위는 변수에 액세스 할 수있는 코드 영역을 나타냅니다. 이를 가시성 이라고도합니다. PHP 범위 블록은 함수, 클래스 및 응용 프로그램 전체에서 사용할 수있는 전역 범위로 정의됩니다.

사용자 정의 전역 변수

함수 또는 클래스 외부의 범위는 전역 범위입니다. PHP 스크립트에 include 나 require 사용하여 다른 스크립트가 포함되어 있으면 범위가 동일하게 유지됩니다. 함수 또는 클래스 외부에 스크립트가 포함되어 있으면 전역 변수가 동일한 전역 범위에 포함되지만 함수 내에 스크립트가 포함되어 있으면 포함 된 스크립트의 변수가 함수의 범위에 포함됩니다.

함수 또는 클래스 메소드의 범위 내에서 global 키워드는 액세스 사용자 정의 전역 변수를 작성하는 데 사용될 수 있습니다.

<?php

$amount_of_log_calls = 0;

function log_message($message) {
    // Accessing global variable from function scope
    // requires this explicit statement
    global $amount_of_log_calls;

    // This change to the global variable is permanent
    $amount_of_log_calls += 1;

    echo $message;
}

// When in the global scope, regular global variables can be used
// without explicitly stating 'global $variable;'
echo $amount_of_log_calls; // 0

log_message("First log message!");
echo $amount_of_log_calls; // 1

log_message("Second log message!");
echo $amount_of_log_calls; // 2

전역 범위에서 변수에 액세스하는 두 번째 방법은 특별한 PHP 정의 $ GLOBALS 배열을 사용하는 것입니다.

$ GLOBALS 배열은 키가되는 전역 변수의 이름과 그 변수의 내용이 배열 요소의 값인 연관 배열입니다. $ GLOBALS가 어떤 범위에 존재하는지주의하십시오. $ GLOBALS는 수퍼 글로벌이기 때문입니다.

즉, log_message() 함수는 다음과 같이 재 작성 될 수 있습니다.

function log_message($message) {
    // Access the global $amount_of_log_calls variable via the
    // $GLOBALS array. No need for 'global $GLOBALS;', since it
    // is a superglobal variable.
    $GLOBALS['amount_of_log_calls'] += 1;

    echo $messsage;
}

global 키워드를 사용하여 전역 변수의 값을 가져올 때 $ GLOBALS 배열을 사용해야하는 이유는 무엇입니까? 주된 이유는 global 키워드를 사용하면 변수를 범위로 가져올 수 있기 때문입니다. 그런 다음 로컬 범위에서 동일한 변수 이름을 다시 사용할 수 없습니다.

슈퍼 글로벌 변수

슈퍼 전역 변수 는 PHP에 의해 정의되며 global 키워드없이 어디서나 사용할 수 있습니다.

<?php

function getPostValue($key, $default = NULL) {
    // $_POST is a superglobal and can be used without
    // having to specify 'global $_POST;'
    if (isset($_POST[$key])) {
        return $_POST[$key];
    }

    return $default;
}

// retrieves $_POST['username']
echo getPostValue('username');

// retrieves $_POST['email'] and defaults to empty string
echo getPostValue('email', '');

정적 속성 및 변수

public 가시성으로 정의 된 정적 클래스 속성은 전역 변수와 기능적으로 같습니다. 클래스가 정의 된 모든 위치에서 액세스 할 수 있습니다.

class SomeClass {
    public static int $counter = 0;
}

// The static $counter variable can be read/written from anywhere
// and doesn't require an instantiation of the class
SomeClass::$counter += 1;

함수는 자체 범위 내에서 정적 변수를 정의 할 수도 있습니다. 이 정적 변수는 함수 범위에 정의 된 일반 변수와 달리 여러 함수 호출을 통해 지속됩니다. 이것은 싱글 톤 디자인 패턴을 구현하는 매우 쉽고 간단한 방법 일 수 있습니다.

class Singleton {
    public static function getInstance() {
        // Static variable $instance is not deleted when the function ends
        static $instance;

        // Second call to this function will not get into the if-statement,
        // Because an instance of Singleton is now stored in the $instance
        // variable and is persisted through multiple calls
        if (!$instance) {
            // First call to this function will reach this line,
            // because the $instance has only been declared, not initialized
            $instance = new Singleton();
        }

        return $instance;

    }
}

$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

// Comparing objects with the '===' operator checks whether they are
// the same instance. Will print 'true', because the static $instance
// variable in the getInstance() method is persisted through multiple calls
var_dump($instance1 === $instance2);


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow