Programming

PHP에서 전역 변수를 선언하는 방법은 무엇입니까?

procodes 2020. 6. 4. 21:15
반응형

PHP에서 전역 변수를 선언하는 방법은 무엇입니까?


다음과 같은 코드가 있습니다.

<?
    $a="localhost";
    function body(){
        global $a;
        echo $a;
    }

    function head(){
        global $a;
        echo $a;
    }

    function footer(){
        global $a;
        echo $a;
    }
?>

한 곳에서 전역 변수를 정의하고 $a모든 기능에서 한 번에 변수에 액세스 할 수있는 방법이 있습니까? global $a;사용하지 않고 ?


$GLOBALS어레이가 대신 사용될 수있다 :

$GLOBALS['a'] = 'localhost';

function body(){

    echo $GLOBALS['a'];
}

로부터 수동 :

현재 스크립트의 전체 범위에 정의 된 모든 변수에 대한 참조를 포함하는 연관 배열입니다. 변수 이름은 배열의 키입니다.


공통 변수가 필요한 함수 집합이있는 경우 전역 속성 대신 속성이있는 클래스를 선택하는 것이 좋습니다.

class MyTest
{
    protected $a;

    public function __construct($a)
    {
        $this->a = $a;
    }

    public function head()
    {
        echo $this->a;
    }

    public function footer()
    {
        echo $this->a;
    }
}

$a = 'localhost';
$obj = new MyTest($a);

변수가 변경되지 않으면 사용할 수 있습니다 define

예:

define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');

function footer()
{
    echo FOOTER_CONTENT;
}

$ GLOBALS 슈퍼 전역 배열에 변수를 추가하십시오.

$GLOBALS['variable'] = 'localhost'; 

전 세계적으로 사용

또는 스크립트 전체에서 액세스 할 수있는 상수를 사용할 수 있습니다

define('HOSTNAME', 'localhost');  

If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:

$variable = 5;

function name()
{
    global $variable;

    $value = $variable + 5;

    return $value;  

}

Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.

config.php

global $variable;

$variable = 5;

other.php

function name()
{
    require_once __DIR__ . '/config.php';
}

You can use $GLOBALS as well. It's a superglobal so it has access everywhere.

$GLOBALS['variable'] = 5;

function name()
{
    echo $GLOBALS['variable'];
}

Depending on your choice you can choose either.


This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.

define("myconstant", "value"); 

class globalVars {

    static $a = false;

    static $b = 0;

    static $c = array('first' => 2, 'second' => 5);

}


function test($num) {

    if (!globalVars::$a) {

        $returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';

        globalVars::$a = true;

    } else {

        $returnVal = 'I forgot';

    }

    return $returnVal;

}

echo test(9); ---> The value of 9 + 0 + 5 is 14.

echo "<br>";

echo globalVars::$a; ----> 1

The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.


You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.

Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.


You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.

$foo = "New";
$closure = (function($bar) use ($foo) {
    echo "$foo $bar";
})("York");

demo | info


Let's think a little different:

class globe{
    static $foo = "bar";
}

And you can use and modify it everyway you like, like:

function func(){
    echo globe::$var;
}

What if you make use of procedural function instead of variable and call them any where as you.

I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.

function host()
{
   return "localhost";
}

You shouldn't be using globals anymore, they are not available in PHP 5.4.

참고URL : https://stackoverflow.com/questions/13530465/how-to-declare-a-global-variable-in-php

반응형