Jump to content

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
https://forums.phpfreaks.com/topic/313636-static-properties/
Share on other sites

Try using the following.  On a side note, 90% of the time I used static properties, I later regretted doing so.  Also, consider changing to PDO.

 

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

 

Link to comment
https://forums.phpfreaks.com/topic/313636-static-properties/#findComment-1589485
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
https://forums.phpfreaks.com/topic/313636-static-properties/#findComment-1589486
Share on other sites

9 minutes ago, NotionCommotion said:

On a side note, 90% of the time I used static properties, I later regretted doing so.

I am only using them for table names between the classes, but thank you

Your solution worked. Could you explain to me why it works and the other way doesn't? thanks

Link to comment
https://forums.phpfreaks.com/topic/313636-static-properties/#findComment-1589487
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
https://forums.phpfreaks.com/topic/313636-static-properties/#findComment-1589488
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
https://forums.phpfreaks.com/topic/313636-static-properties/#findComment-1589500
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.