【问题标题】:In class public variable is NULL在类公共变量为 NULL
【发布时间】:2015-07-17 16:02:49
【问题描述】:

我有一个类,我想在一个函数中设置$offset变量,并得到另一个函数

    public $db, $_offset, $_limit;

    public function Pagination($offset,$limit)
    {
        $limit = 2;
        $page = isset($_GET['page']) ? abs((int)$_GET['page']) : 1;
        if ($page <= 0)
        {
            $page = 1;
        }
        $offset = $page;
        $this->_offset = $offset; // set value for this->_offset
        $this->_limit = $limit; // set value for this->_limit
        return true;
    }

    public function SearchAd($value)
    {
        global $offset,$limit;
            var_dump( $this->_limit); // this will return NULL
            var_dump( $this->_offset); // this will return NULL
     }

怎么了?

【问题讨论】:

  • 有执行代码吗?你在SearchAd()之前使用Pagination()函数吗?
  • 是的,MyClass 类 { public $db,$limit,$offset public Pagination(..) {...} public SearchAd(..) {..} }
  • 另外,尽量避免在你的类中使用全局变量,你会破坏封装。
  • 使用私有变量,然后将它们与 $this->db... 一起使用

标签: php class variables global public


【解决方案1】:
<?php
class Paginator {

   public $db, $_offset, $_limit;

   public function __construct($offset, $limit = 20){

       $offset = isset($_GET['page']) ? abs((int)$_GET['page']) : 1;

       if ($offset <= 0)
       {
           $offset = 1;
       }

       $this->_offset = $offset; // set value for this->_offset
       $this->_limit = $limit; // set value for this->_limit
       return true;
   }

   public function SearchAd($value)
   {
       var_dump( $this->_offset); // this will return NULL
       var_dump( $this->_limit); // this will return NULL
   }
}

 $pagination = new Paginator(5,10);
 $pagination->SearchAd("asd");

结果: 1 10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-31
    • 2014-10-09
    • 2014-02-17
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2016-01-01
    • 2010-09-20
    相关资源
    最近更新 更多