简体   繁体   中英

PHP Private Variable issue

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?

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.

根据此链接,您的关键字__constructor是否应改为__construct?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM