dpy15285 2016-03-17 07:38
浏览 48

PHP私有变量问题

I try to get value of a private variable (limit), but I get the following error:

Fatal error: Uncaught Error: Using $this when not in object context in /home/vagrant/Code/wp/wp-content/plugins/StorePress/app/library/Pagination.php on line 36

My Class:

class Pagination
  {
   private $limit = 0;
   private $limit_start = 0;
   private $total = 0;

 /**
  * Generate Pagination for Products
  * @param $pagination
  * @return string
  */
public function __constructor($pagination = null)
{
    $this->limit = $pagination['limit'];
    $this->lim_start = ($pagination['start']) ?: null;
    $this->total = $pagination['total'];
}

public function generatePagination()
{
   echo $this->limit;
}

Here, I'm trying to print "$this->limit", a private variable, but it's not allowed to print the value that are assigned by the "__constructor".

Is there anything wrong in my code or is there any other solution to get that value?

  • 写回答

2条回答 默认 最新

  • duanfan9859 2016-03-17 07:46
    关注

    I think, that the problem is in your OOP construction. You cannot echo $this private variable, when you don't create class object as first. So the solution might be:

    class Pagination
      {
       private $limit = 0;
       private $limit_start = 0;
       private $total = 0;
    
     /**
      * Generate Pagination for Products
      * @param $pagination
      * @return string
      */
    public function __constructor($pagination = null)
    {
        $this->limit = $pagination['limit'];
        $this->lim_start = ($pagination['start']) ?: null;
        $this->total = $pagination['total'];
    }
    
    public function generatePagination()
    {
       return $this->limit;
    }
    

    and then in your code, where you need to echo the limit value, you can use:

    $pagination = new Pagination();
    echo $pagination->generatePagination();
    

    At first line, you will create new Pagination() object and in the second line, you will return the $limit value from your generatePagination class function.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答