Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从其他文档访问全局变量_Php_Class_Oop - Fatal编程技术网

Php 从其他文档访问全局变量

Php 从其他文档访问全局变量,php,class,oop,Php,Class,Oop,我从PHP中的OOP开始,我对全局变量有一个问题 我当前的结构示例: test.php需要globals.php,还包括classes.php globals.php有以下代码: global $something; $something = "my text"; 而classes.php如下所示: global $something; class myClass { public $abc = "123"; public $something; public

我从PHP中的OOP开始,我对全局变量有一个问题

我当前的结构示例:

test.php
需要
globals.php
,还包括
classes.php


globals.php
有以下代码:

global $something;
$something = "my text";

classes.php
如下所示:

global $something;

class myClass {
    public $abc = "123";
    public $something;

    public function doSomething() {   
        echo $this->abc."<br>";
        echo $this->something;
    }
}

$class = new myClass();
$class_Function = $class->doSomething();

print_r($class_Function);
global$something;
类myClass{
公共$abc=“123”;
公共物品;
公共函数doSomething(){
echo$this->abc。“
”; echo$this->something; } } $class=新的myClass(); $class_Function=$class->doSomething(); 打印(类功能);

最后,
test.php
仅显示“123”


我尝试对
globals.php
使用“include()”而不是“require”,但没有成功。在
classes.php中包含
globals.php

something
从未初始化。全局
$something
完全超出范围,与类属性
$this->something
无关。如果需要访问函数或方法中的全局,则需要将其声明为全局:

public function doSomething() {   
        global $something;
        echo $this->abc."<br>";
        echo $something;
    }
然后您可以在代码的任何部分访问它:

echo SOMETHING;
另见:
还有

$this->something!=$something
@u-mulder为什么不呢?因为
$this->something
是一个类的属性,
$something
是一个变量。如果你正在学习OOP,那么就完全忘记全局变量,并询问正确的方法来完成你真正想做的事情。
$this->something
正在访问一个类的属性。类对任何外部变量一无所知。感谢您的响应。我如何在课堂上访问
内容
<代码>公共物品
抛出此错误:
解析错误:语法错误,意外的“SOMETHING”(T_字符串),期望变量(T_变量)
对于定义,您不需要在函数内部声明。只使用
回音
(它不需要
$
)我使用
public$something=something获得一种方法是,可以使用“定义”命令初始化属性。
echo SOMETHING;