在类中,public变量为NULL

时间:2021-11-18 23:29:28

I have a Class, and I want to the $offset variable set in a function, and get a another function

我有一个类,我想在函数中设置$ 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
     }

What's wrong with?

怎么了?

1 个解决方案

#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");

result : 1 10

结果:1 10

#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");

result : 1 10

结果:1 10