Using $ this when not in object context - PHP

2

I have explored several similar questions before sending this post, so I am sure of what I am doing.

I am creating a web application written in PHP, where I have some classes that I usually call, such as using Url::exists($alias) .

Well, I'm getting the error using $this when not in object context , and I could not solve it. It's already been more than 2 hours looking for a solution.

Code:

class Url extends App {

private $db;
private static $alias = null;
private static $list = null;
private static $url = null;
private static $clicks = 0;
private static $name = null;
private static $password = null;

public function __construct() {
$this->db = json_decode(file_get_contents('/../' . $this->getConfig()->get('DB_PATH')), true);
}

public static function exists(string $alias) {
foreach($this->db as $url) {
 if($url['ALIAS'] == $alias) {
  return true;
 }
}
return false;
}

Where the error is on line $this->db .

Thanks for your answers.

    
asked by Derek Nichols 04.08.2017 в 02:43
source

1 answer

3

$this refers to the context of the current instance of the object . The methods static do not belong to the instance of the object .

You have 2 options:

1- You add the object to the class instance removing the static of the method statement:

 class Url extends App {

    public function exists(string $alias) {
      foreach($this->db as $url) {
       if($url['ALIAS'] == $alias) {
          return true;
        }  
     }
}

2- You send the instance of the object as a parameter to obtain the properties of the object you need:

class Url extends App {
         // ..

    public static function exists(Url $urlInstance, string $alias) {
      foreach($urlInstance->db as $url) {
       if($url['ALIAS'] == $alias) {
          return true;
        }  
     }
}

Usage:

$url = new Url();
Url::exists($url,"ruta");
    
answered by 04.08.2017 в 04:09