N
N
Ninazu2018-11-23 09:37:44
PHP
Ninazu, 2018-11-23 09:37:44

How to implement the filling of static properties in inherited classes from the parent?

Something I got confused with static. More precisely, with how it can be used to make a singleton.

<?php

/** Описание обьекта B */
class B extends Base {}

/** Описание обьекта А */
class A extends Base {}


class Base {

  public static $comment;
  
  public static $name;
  
  public function __construct(){
    //Нет смысла выполнять этот код для каждого экземпляра класса
    //так как комментарий и имя статичны для класса
    
    //if(is_null(static::$name)){
      $reflect = new ReflectionClass(static::class);
      static::$comment = $reflect->getDocComment();
      static::$name = $reflect->getShortName();
      echo "<br>Получение Reflect данных для класса ".static::$name;
    //}
  }
}


echo "<pre>";

for($i=0;$i<3;$i++){
  $list = [];
  
  foreach(['A','B'] as $className){
    $class = new $className();
    $list[$class::$name] = $class::$comment;
  }
  
  echo "<br>";
  print_r($list);
  echo "<hr>";
}

PHP Fiddle
As you can see from the code, it makes no sense to initialize static properties for each object, they must be initialized once for each class

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Ermilichev, 2018-11-23
@Masas

class Foo{

    public static function changeTest()
    {
  static::$test = '321';
    }
}

class Bar extends Foo
{
  public static $test = 123;
}

var_dump(Bar::$test);
Bar::changeTest();
var_dump(Bar::$test);

But this is a very bad approach. The parent class should not know anything about the child at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question