【问题标题】:include files which has same variable names包含具有相同变量名的文件
【发布时间】:2015-09-17 18:29:22
【问题描述】:

A.php

define("_a_","hey!");

B.php

define("_a_","wow!");

index.php

function getFile($type) {
  include_once($type . ".php");
  echo _a_;
}

调用 getFile

getFile(A); //--> Output "hey!"
getFile(B); //--> Output "hey!" HERE IS THE PROBLEM, SHOULD ECHO "wow!"

然后我交换了调用函数的顺序

getFile(B); //--> Output "wow!"
getFile(A); //--> Output "wow!" HERE IS THE PROBLEM, SHOULD ECHO "hey!"

感谢大家的帮助

【问题讨论】:

  • 查看答案,如果有帮助,请将其标记为已接受 - StackOF 社区将感谢您

标签: php


【解决方案1】:

来自PHP official documentation

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )  

在运行时定义一个名为 CONSTANT

因此,如果它定义了不可更改的值,则意味着您无法在运行时更改该值。

编辑: 您可以使用变量从包含的文件中获取数据。当您包含脚本时,您基本上是在创建新脚本,并从包含的文件中复制和粘贴内容并执行该新脚本。 Passing a variable from other script - PHP

【讨论】:

  • 这是真的,我可以接受,但这不应该是问题,因为我将文件动态包含在函数中。我的意思是当传递“A”时,getFile 函数包含 A.php,如果我传递“B”,那么 getFile 应该只包含 B.php
  • 只是为了扩展what is a constanta constant is an identifier with an associated value which cannot be altered by the program during normal execution。你可以阅读更多关于php's implementation here的信息。
  • @user3645649 在 php 常量页面上:Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. 在函数中定义常量仍然是在全局范围内定义的。
  • 感谢@JonathanKuhn。我需要这样做,我该怎么做?
  • 创建变量怎么样?
猜你喜欢
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
  • 2017-09-09
  • 1970-01-01
  • 2014-08-25
相关资源
最近更新 更多