简体   繁体   English

如何使用全局变量初始化class属性?

[英]How to use the global variable to initialize the class property?

I'm using PHP 7.2.6 我正在使用PHP 7.2.6

I know that "A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function". 我知道“在函数外部声明的变量具有全局范围 ,并且只能在函数外部访问”。

I want to the already declared global variable into my class. 我想将已经声明的全局变量放入类中。

I want to initialize the class property using this global variable. 我想使用此全局变量初始化class属性。

For it, I tried below code 为此,我尝试下面的代码

<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

class foo
{
    var $foo;

    function __construct()
    {
        $this->foo = $str;
    }
}

$foo = new foo();
echo $foo->foo;
?>

I got following notice in my browser : 我在浏览器中收到以下通知:

Notice: Undefined variable: str in hello.php on line 14

I'm not understanding why I'm getting this notice. 我不明白为什么收到此通知。

I'm not accessing the global variable $str inside any function. 我没有在任何函数内访问全局变量$str I'm using it inside a class. 我在课堂上使用它。

Please help me in this regard and also explain me how should I use the global variable to initialize the class property? 请在这方面帮助我,并向我解释如何使用全局变量初始化class属性?

To access a global variable you need to use the global variable with global keyword, Secondly your modifier and class shares the same name which afaik will confuse the compiler see the below snippet 要访问全局变量,您需要使用带有global关键字的global变量, 其次,您的修饰符和类使用相同的名称,而afaik会使编译器感到困惑,请参见以下代码段

Nope It doesn't 不,不是

   <?php

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

class foo
{
    public  $foo;

    function __construct()
    {
        global $str;
        $this->foo = $str;
    }


}

$foo = new foo();
echo $foo->foo;
?>

Snippet 片段

Why not to use global variables 为什么不使用全局变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM