mikelovelyuk
mikelovelyuk

Reputation: 4152

How do I set and use a protected static property?

Here is an abstract class I have to use;

abstract class Model
{
    protected static $_tableName  = false;

    public static function tableName()
    {
        return static::$_tableName;
    }

    public static function find($idOrWhere = false, $params = array(), $limit = false)
    {
        $sql    = "SELECT * FROM " . static::tableName();

I can't seem to set the _tableName, static::tableName(), or tableName() in my own class;

class Payments extends Model {

public function __construct()
{
    $this->_tableName  = 'payments';
}

That's not doing anything! It's not set the tableName to payments. And I can't figure out how to use the method tableName() either.

Upvotes: 2

Views: 1603

Answers (3)

origaminal
origaminal

Reputation: 2075

A property declared as static cannot be accessed with an instantiated class object (though a static method can).

Static properties cannot be accessed through the object using the arrow operator ->.

http://php.net/manual/en/language.oop5.static.php

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed.

According to this material your classes should be reworked that way.

abstract class Model
{
    protected static $_tableName  = false;

    public static function find($idOrWhere = false, $params = array(), $limit = false)
    {
        $sql = "SELECT * FROM " . self::tableName();
        ...
    }

    private static function tableName()
    {
        if (!static::$_tableName) {
              throw new \RuntimeException('No table name provided');
        }

        return static::$_tableName;
    }

class Payments extends Model {

    protected static $_tableName  = 'payments';
}

Btw, __contruct is called on object instantiation and you should not set any static properties values there.

Upvotes: 2

knittl
knittl

Reputation: 265171

Static members have to be accessed on the class, not on an instance:

class Payments extends Model {

  public function __construct()
  {
     Payments::$_tableName  = 'payments';
  }
}

Upvotes: 1

nowy
nowy

Reputation: 394

You are trying to access _tableName in a non-static way (I.e. $this->_tablename) even though you've declared it as static.

You need to access it like so:

self::$_tableName

OR, for late static binding:

static::$_tableName

Overall, you should avoid the use of static classes as much as possible, mainly due to testing purposes.

Upvotes: 4

Related Questions