Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private static variables in php class

I have a few classes that are often run through var_dump or print_r.

Inside these classes I have a few variables that are references to other, rather large objects that only ever has one instance of each and are only used inside the classes (outside the classes have their own reference to these classes) I do not wish these classes printed in the output, so I have declared them as private static which is working fine.

But my IDE (PHPstorm) is flicking up an error-level alert with Member has private access when I access them through self::$ci->...

I am wondering if this is a bug in the IDE, highlighting because it's probably a bug (aka it's static but nothing outside the class can access it, why would you want to to do that?), or because there is actually something syntactically wrong with it?

As an example here is part of the class, Note that =& get_instance(); returns a reference to the Code Igniter super object

private static $ci = null;

public function __construct(){
    self::$ci = self::$ci =& get_instance();
}

public function product() {
    if ($this->product == null) {
        self::$ci->products->around($this->relative_date);
        $this->product = self::$ci->products->get($this->product_id);
    }
    return $this->product;
}
like image 850
Hailwood Avatar asked Nov 29 '12 21:11

Hailwood


People also ask

Can static be private in PHP?

This is separate from the visibility of that variable - a public static property exists once per class, and can be accessed from everywhere; a private static property exists once per class, but can only be accessed from inside that class's definition.

How can use static variable in class in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

How can I access private static variable in PHP?

Accessing the value of a static variable is similar to accessing for a class constant: You either use the type name (outside of or within the class) or the keyword self , both followed by the scope resolution operator ( :: ) and the name of the static variable, starting with $ .

Can you have a private static variable?

Just like an instance variables can be private or public, static variables can also be private or public.


1 Answers

In your product() method you're trying to access the private member self::$ci. Your IDE thinks that this method can be accessed anywhere, and detects a conflict with the private static member $ci.

like image 67
Pierre Criulanscy Avatar answered Sep 18 '22 16:09

Pierre Criulanscy