PHP static variables in abstract classes

I am working on a project where I would like to declare a static member variable inside an abstract base class. I have a Model class, an intermediate Post class, and finally a Post-site class that looks like this:

abstract class Model { protected static $_table = null; protected static $_database = null; ... } abstract class PostModel extends Model { public function __construct() { if ( !isset(self::$_table) ) { self::$_table = 'some_table'; } parent::__construct(); } ... } class SitePostModel extends PostModel { public function __construct() { if ( !isset(self::$_database) ) { self::$_database = 'some_database'; } parent::__construct(); } ... } 

I would like to make it obvious from the Model class that the $ _table and $ _database members are required. However, $ _table is really static in terms of the PostModel class, and $ _database is really static in terms of the SitePostModel class.

Is this a legitimate way to achieve my goal? Does the declaration of static variables in the model itself mean that they should exist only once for an abstract base class or only once for a real instance of the class?

+6
source share
2 answers

Is this a legitimate way to achieve my goal?

Not. It does not work, so it does not perform a basic test for legitimacy.

Does the static variable declare in the model itself that they must exist only once for the abstract base class or only once for the actual instance of the class?

Static variables are global; they exist once. In your case, for each class name. If you have three class names, you will have three (global) variables. The protected keyword controls the visibility / scope of three static variables:

 <?php class A { protected static $v = 'red'; public static function get() { return self::$v . ' - ' . static::$v;} } class B extends A { protected static $v = 'blue'; } class C extends B { protected static $v = 'green'; } echo C::get(); # red - green 
+1
source

I recently ran into the same problem and came up with the same solution - set the parameters to static variables and accessed them using a static keyword. It also works in cases where you have default settings (for example, the number of lines per page) that you can override in subclasses. It seemed to me in the most intuitive and effective way.

Alternatives I reviewed:

  • Use the static abstract getter function. This requires more lines of code and more function calls.
  • Store the parameter in a non-static member variable and let the constructor of the child class worry about it. I rejected this parameter because my child classes would not need a constructor otherwise.
0
source

Source: https://habr.com/ru/post/899482/


All Articles