PHP变量问题!

0 php variables

所以我有一个PHP变量,它的值被另一个PHP文件取代.例:

$var = "~~~OtherVariable~~~";
Run Code Online (Sandbox Code Playgroud)

如果我回显这个变量,它会输出相应的字符串.例:

echo $var; //prints out "This is a string of text";
Run Code Online (Sandbox Code Playgroud)

所以看起来到目前为止一切正常,我的PHP变量($var)显示它实际上包含字符串"This is a string of text"而不是"~~~OtherVariable~~~".

现在问题来了,我想在另一个PHP函数中使用这个PHP变量我在其他地方(在同一页面上),我想要变量($var)值"This is a string of text",而是函数正在读取它"~~~OtherVariable~~~",这不是我想要的是!

有没有办法让函数读取变量"This is a string of text"而不是"~~~OtherVariable~~~"

谢谢Guys&Gals

编辑:这是代码块:

$string = "~~~ItemTitle~~~"; /*Another php file looks for any string in 
this file with "~~~ItemTitle~~~" and replaces it with another block of 
text, ie. "This is a string of text, http://www.google.ca" */

//Then I have a little function to look for any links inside of a string of text
function do_reg($text, $regex)
{
   preg_match_all($regex, $text, $result, PREG_PATTERN_ORDER);
   return $result[0];
}

$regex = '\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]';

$regex = '$'.$regex.'$i';

$A =do_reg($string, $regex); /* This is where I tell it what string I want 
it to look into for any URL's */
foreach($A as $B)
{
   echo "$B<BR>"; //Prints out just the URL
}
Run Code Online (Sandbox Code Playgroud)

但是,当我告诉它时,它也会在$string变量中查找它,"~~~ItemTitle~~~"而不是它被替换为的文本字符串.

And*_*ore 7

听起来你有一个变量范围问题.

当您include使用文件时,第二个文件中的代码与您的include语句所在的代码在相同的范围内运行.

请考虑以下代码:

first.php

<?php
$var = 'Apples';
include('second.php');

echo ' and ', $var;
Run Code Online (Sandbox Code Playgroud)

second.php

<?php
$var = 'Oranges';
echo $var;
Run Code Online (Sandbox Code Playgroud)

当您的代码在全局范围内运行时,first.php将输出Running .一旦被代码覆盖,就无法获得原始值,因为它们是同一范围内的相同变量."Oranges and Oranges"second.php$varsecond.php


现在考虑以下内容:

third.php

<?php
function include_isolated($file) {
    include($file);
}

$var = 'Apples';
include_isolated('second.php');
echo ' and ', $var;
Run Code Online (Sandbox Code Playgroud)

运行third.php将输出"Oranges and Apples",second.php然后将在函数范围内运行include_isolated().在这种情况下,$var并且$var是两个单独的变量,因为它们不在同一范围内.


如果您需要全局范围(定义的值)third.php,您可以使用超级全局$GLOBALS来访问它:

$globalVar = $GLOBALS['var']; // $globalVar = "Apples"
Run Code Online (Sandbox Code Playgroud)

您还可以修改include_isolated()函数以使其成为$var全局:

function include_isolated($file) {
    global $var;
    include($file);
}
Run Code Online (Sandbox Code Playgroud)

但是,当这样做时,$var将再次成为全局范围变量.这将使$var第二个文件中的赋值覆盖第一个文件中的值.其他变量不会受到影响.


有关变量范围的更多信息,请阅读PHP文档.