Jump to content

Static properties


TechnoDiver

Recommended Posts

Good morning Freaks, I hope you're all having a productive week. I've a question about an issue I'm having accessing static properties. I've been doing some reading on them but haven't yet deployed one successfully. I have a bunch of classes and I want to make the database query tables all static so they can be used cross-class, so to speak.

Here's a sample attempt ->

class Post {
  private $conn;
  private $user_obj;
  public static $table = "posts";

  public function __construct($conn, $username) {
      $this->conn = $conn;
      $this->user_obj = new User($conn, $username);
      // $this->table = "posts";

  }

and accessing it here ->

public function getBreakingNews() {
  $query = mysqli_query($this->conn, "SELECT * FROM self::$table WHERE type='breaking' ORDER BY RAND()");

This gets me an error that $table doesn't exist as does using Post::$table. When I assign $this->table = 'posts' (the commented out line in __construct) and access it by $this->table all works great. What am I doing wrong that it won't find that public static property?

In the manual there's this example, which I feel like I've stayed true to ->

class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}

.....

print Foo::$my_static . "\n";

The only difference I see is that they're printing the value and I'm trying to use it in a database query. Can anyone guide me through this mistake I'm apparently making and can't see? I've tried both self::$table and Post::$table, self::table and Post::table, every permutation I can think of but still the variable is saying it's unassigned. Share your knowledge please

Link to comment
Share on other sites

I wish I could have edited this comment so apologies for back to backs.

I decided to make an instance variable to use in the methods of the class itself and keep the static for other classes that need that table. And see if that would work. ->

<?php 
  class Post {
      private $conn;
      private $user_obj;
      public static $table = "posts";

      public function __construct($conn, $username) {
          $this->conn = $conn;
          $this->user_obj = new User($conn, $username);
          $this->table = self::$table;
          //$this->table = "posts";

      }

And I thought this was a great idea; but I'm getting Notices that of trying to access a static property as non static. I'm using

public function getBreakingNews() {
  $query = mysqli_query($this->conn, "SELECT * FROM $this->table WHERE type='breaking' ORDER BY RAND()");

It's confusing to me why it says that. It means (to me) that '$this->table' and 'self::$table' aren't separated entities. My understanding was that $this referred to the instance and 'self' referred to the class. So why are places that I've instantiated it at giving me this message?

I don't understand it and it's nothing an answer you can readily resolve on search engines. Hoping someone can break this down for me

Link to comment
Share on other sites

49 minutes ago, TechnoDiver said:

This gets me an error that $table doesn't exist as does using Post::$table

When looking for variables to interpolate in a string, PHP identifies them by the $.  Your self:: or Post:: is not being considered as part of the variable because they are before the $.  So PHP is looking for a local variable $table which doesn't exist and your query would be "SELECT * FROM self:: WHERE ...".

To use your static variable, you need to concatenate it, not rely on interpolation.

$query = mysqli_query($this->conn, "SELECT * FROM ".self::$table." WHERE type='breaking' ORDER BY RAND()");

 

8 minutes ago, TechnoDiver said:

It means (to me) that '$this->table' and 'self::$table' aren't separated entities.

They aren't.  Your class has only one variable named $table, but it's "class-level" rather than "instance-level".  You use $this-> to access instance-level variable and a static reference (ie, self::) to access class-level variables.   Using $this-> to access a static variable is improper.

  • Like 1
Link to comment
Share on other sites

Where static really shines is when you using an Active Record Design Pattern (I would assume other patterns are the same way, but this is the only pattern that I have used so far), for example:

The Data Object Class

class DatabaseObject // Extended by the children class:
{
    static protected string $table = ""; // Overridden by the calling class:
    static protected array $db_columns = []; // Overridden by the calling class:
    static protected array $objects = [];
    static protected array $params = [];
    static protected $searchItem;
    static protected $searchValue;

// More code....

A Children Class example

class CMS extends DatabaseObject
{
    protected static string $table = "cms"; // Table Name:
    static protected array $db_columns = ['id', 'user_id', 'thumb_path', 'image_path', 'Model', 'ExposureTime', 'Aperture', 'ISO', 'FocalLength', 'author', 'heading', 'content', 'data_updated', 'date_added'];

// More Code....

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.