Mixed results with is_page() WordPress function, when using $this, or self

You’ve shared that this is how the member variable is defined:

class PropertySearch {
    private static $listing_details_template_name;

This means it is a private static variable and can be accessed using static accessor such as self::$listing_details_template_name or PropertySearch::$listing_details_template_name.

Additionally, you’ve declared that it’s a private member variable, so it can only be referred to from within the same class via self::.

Why not $this?

$this would be innapropriate because $this refers to a specific object, not a class, and static member variables do not belong to objects, they belong to the definition of a class, specifically PropertySearch.

Remember, PropertySearch is not an object, it’s a class, a class is a definition that’s used to create instances of objects. I may be human but it would be a mistake to say human::$name="Tom"; because that’s saying that all humans are named Tom, not just me specifically.

Likewise $this->listing_details_template_name heavily implies that different PropertySearch objects can have different listing detail templates, and that it’s a dynamic changing value, not a static value shared by all objects that use that class.

That is why you get this message:

Notice: Accessing static property PropertySearch::$listing_details_template_name as non static

Ironically, if you changed it to be a dynamic member variable it would work with $this and it would no longer be appropriate to use self.

Methods

Instead of directly accessing it why not use a method? Then you can add filtering and other logic.

TLDR

  • static member variables are on classes
  • dynamic member variables are on objects
  • Use $this->variablename or $object->variablename for dynamic member variables
  • Use self::$variablename or ClassName::$variablename for static member variables
  • Consider using a method as an alternative option