Home >Backend Development >PHP Tutorial >关于php include变量作用域的说明

关于php include变量作用域的说明

WBOY
WBOYOriginal
2016-06-23 13:36:24864browse

作者:zhanhailiang 日期:2015-04-17

首先,请阅读include,其中重点说明了“include所包含的代码继承了 include 所在行的变量范围”:

当一个文件被包含时,其中所包含的代码继承了 include 所在行的变量范围。从该处开始,调用文件在该行处可用的任何变量在被调用的文件中也都可用。不过所有在包含文件中定义的函数和类都具有全局作用域。

这意味着,include里的代码可以访问到所在行处能访问到的所有相关变量。

如下,我将编写test.php test1.php来验证一种很诡异的写法:

test.php

<?phpclass A {     public function __construct() {        include 'test1.php';    }   }$a = new A();var_dump($a);

test1.php

<?php $this->a = 1;                                                                                 $this->b = 2; 

执行输出如下:

object(A)#1 (2) {  ["a"]=>  int(1)  ["b"]=>  int(2)}

这即证明了include文件的中代码确实继承了 include 所在行的变量范围,其可以访问到$this变量。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn