zoukankan      html  css  js  c++  java
  • php中变量引用&不可与global共同使用

      问题来源,新公司debug。

      程序中代码大致如下

    class Ci {
    
    	private static $instance = NULL;
            public $name = 'hello';
            public $load = null;
    
            public function __construct()
            {
            	self::$instance = &$this;
            	$this->load = new Load;
            	mlog(self::$instance, __LINE__);
    			//other code ....
    			$this->name = 'my name';
            }	
    
    	public static function &getInstance()
    	{
    		return self::$instance;
    	}
        }
    
        class My extends Ci{
    
            public function __construct()
            {
    		parent::__construct();
    		$this->model = new Model;
            }
        }
        class Model {
    
    	public function __construct() 
    	{
    		$this->name = _get(); // null
    		mlog("success, and model->name = {$this->name}", __LINE__);
    	}
      }
      class Load {
    
    	public $name = 'I am Load class';
    
    	public function getName() 
    	{
    		return $this->name;
    	}
      }
    
        $CI =& get_instance();
        // mlog($CI->name); //hello
        // mlog($CI->load->getName()); //I am Load class
        mlog($CI, __LINE__);
      $CI = new My;
      mlog($CI, __LINE__);
    	
    
      function _get() 
      {
    	//call static variables
    	global $CI; //non-boject
    	//return $CI->load->name(); // 500
    	return $CI->name; //notice
      }
    
      function &get_instance()
      {
    	return Ci::getInstance();
      }
    
      function mlog($content, $line = __LINE__,$display = true)
      {
    	$next_line = "<br />";
    	if (php_sapi_name() === 'cli') {
    	  $init = '';
    	  $next_line = "
    ";
    	} 
    	if ($display) {
    	  echo $init;
    	  echo "in line: $line" . $next_line;
    	  print_r($content);
    	  echo $next_line;
    	}
      }
    

      相信朋友们可以看出来,这是CI框架中的一部分,开发者为了封装方法所以在helper中使用如下代码

    <?php
        $CI =& get_instance();
    
        function demo() 
        {
             global $CI;
             //return $CI->mehton;          //notice
             //return $CI->class->method;//500   
        }
    

      服务器直接报了500。通过我第一部分的代码与注释,应该可以得出以下结论:在function的scope中global $ref是拿不到该引用的,php手册中也有说明,详情请看。干啥都不能不细心啊,好好学习基础^_^

  • 相关阅读:
    Poemscape|Beta阶段第九天
    Poemscape|Beta阶段第八天
    Poemscape|Beta阶段第七天
    Poemscape|Beta阶段第六天
    Poemscape|Beta阶段第五天
    Poemscape|Beta阶段第四天
    Poemscape|Beta阶段第三天
    luffy-后台Response和异常封装、跨域问题解决、前后台打通、xadmin后台管理
    python项目的requirement.txt的生产的和使用
    路飞项目之项目前期准备
  • 原文地址:https://www.cnblogs.com/jixingke/p/7573042.html
Copyright © 2011-2022 走看看