Home php教程 php手册 概论为什么PHP全局变量不能生效

概论为什么PHP全局变量不能生效

Jun 13, 2016 am 11:10 AM
php cannot Why overall situation variable exist newbie hour Take effect

对于一个新手在实际操作

但在实际操作时,会接连碰到几次全局变量无效的郁闷的事,下面就重点看一下PHP全局变量不能生效的原因及解决办法。

1.PHP全局变量不能生效错误重现

问题出现在用我的简易框架时,在view中使用原来第三方定义好的函数时(此函数比较独立),下面模拟一下:

t1.php

  1.  ?  
  2. run(); //执行  
  3. function run(){  
  4. include 'func.php';  
  5. showGlobal();  
  6. }  
  7. ?> 

func.php1

<ol class="dp-xml">
<li class="alt"><span><span class="tag"><span> ?  </span></span></span></li>
<li>
<span>$</span><span class="attribute">vars</span><span> = </span><span class="attribute-value">'I am global!'</span><span>;  </span>
</li>
<li class="alt"><span>function showGlobal(){  </span></li>
<li><span>global $vars;  </span></li>
<li class="alt"><span>print('我使用全局变量:'.$vars);  </span></li>
<li><span>}  </span></li>
<li class="alt">
<span class="tag">?></span><span> </span>
</li>
</ol>
Copy after login

很简单的两个文件(第一次发现问题时,远比这复杂,在一层层排错后,得出最少化的问题重现环境),func.php是定义好的第三方函数,该函数使用了一些全局变量,如果这时把这两个文件放在一起,执行一下t1.php,会发现showGlobal里的$vars是显示不出来的,global失效了?

2.PHP全局变量不能生效错误原因

搜索后发现,php.net上很早就有人提出过,也有人给出了解释:
原来,在t1.php的run函数中include func.php时,func.php中的变量$vars的作用域只是在run之内,而在showGlobal中使用global声明的$vars是要求属于t1.php的不是run函数的,所以为空)

3.PHP全局变量不能生效解决方法

知道原因后,解决就很简单,可以把include 从run中移出来,这样,func.php中的$vars就属于t1.php了;也可以在run里用global声明一下$vars,这样也可以把原来属于run的$vars声明为全局(属于t1.php);

虽然问题可以简决,但用起来还是很不爽, 因为在我的phpec框架中,include的情况比较普遍,不可能把view中按需include的移到外层去,使用global的话,我在使用第三方函数时,又不会也不想去了解它用了什么全局变量,而且,层次结构一多,就….

PHP全局变量不能生效的原因总结:

1)尽量减少多级和函数中include文件.

2)尽量不用全局变量


Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

What is the difference between php framework laravel and yii What is the difference between php framework laravel and yii Apr 30, 2025 pm 02:24 PM

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Why should you listen Why should you listen Apr 21, 2025 pm 09:00 PM

Concordium: A public first-level blockchain platform that takes into account privacy and compliance is a public first-level blockchain platform. Its core lies in the clever integration of identity verification with privacy and regulatory compliance. Founded in 2018 by Lars Seier Christensen, the platform’s core technology embeds cryptographic identities at the protocol level of each transaction. This unique design ensures responsibility traceability while protecting user privacy, effectively solving the problem of conflicts between anonymity and regulatory requirements in the blockchain field. To alleviate this problem, Concordium utilizes Zero Knowledge Proof (ZKP) technology, allowing users to verify specific identity attributes without the need to disclose unnecessary personal information. This means that, despite every

Explain how to use sessions for user authentication. Explain how to use sessions for user authentication. Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles