Home  >  Article  >  php教程  >  php全局变量和正则表达式错误解决方案

php全局变量和正则表达式错误解决方案

WBOY
WBOYOriginal
2016-06-06 19:42:251093browse

在java,c,c里面都有严的变量作用域 ,php则没有明确的(不准确)作用域,比如一个方法外面定义的变量- 在方法里面是引用不了的 解决这个的方法 可以用超全局变量 request session post 之类的magic函数或者global,重点是global!一个普通的php文件里面 如

在java,c,c++里面都有严格的变量作用域 ,php则没有明确的(不准确)作用域,比如一个方法外面定义的变量-值 在方法里面是引用不了的

解决这个的方法 可以用超全局变量  request session post  之类的magic函数或者global,重点是global!一个普通的php文件里面 如下写法是没有问题的:

$a = 1;
$b = 2;
function Sum()
{
    global $a, $b; 
	echo $a."  ",$b." ";
	
    $b = $a + $b;
}
Sum();
echo $b;//3
return $b;



但是在一个php封装的类里面是不行的

class MyClass {
private  $str = "Hello, World";
    function my_print() {

        global $str;

        print "str:".$str;

    }

}


只有这样:

class MyClass {

    function my_print() {

        global $str;

        print "str:".$str;

    }

}

  $str = "Hello, World";
$myclass = new MyClass();//
$myclass->my_print();//Hello, World
网上查了很久 发现可以使由于作用域问题导致 global无效

在一些include的时候会导致作用域变化


如果是在同一个类里面需要用的全局变量 可以尝试下面这种方法




<?php global $operator_stack;
global $operation_stack;
$operator_stack=array();
$operation_stack=array();
class index_expressionTrans
{
function test1( )
{
//array_push($operator_stack,1);
  global $operator_stack;

array_push($operator_stack,1);
}
function test2( )
{
	  global $operator_stack;

array_push($operator_stack,2);
}
}

$classtest=new index_expressionTrans();
$classtest->test1();
$classtest->test2();
print_r($operator_stack);
//Array ( [0] => 1 [1] => 2 ) 
exit;
   下面记录用php
<span>preg_match</span>
匹配正则表达式老是出错的问题

明明java已经调试好的正则表达式在这个方法里面就不能用了

解决方案:  在你的正则表达式开头和结尾加上“/      /”;


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