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 = "\n";
	} 
	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手册中也有说明,详情请看。干啥都不能不细心啊,好好学习基础^_^

posted @ 2017-09-22 08:59  郭延龙  阅读(291)  评论(0编辑  收藏  举报