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

转载于:https://www.cnblogs.com/jixingke/p/7573042.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值