Search code examples
phpvariablesstaticnon-static

how to change non static variable to static method in php


I am calling constant variable like this, but it show errors, How to solve this? I don't calling it like these code below,

$b = new A()
$b::$test

here my code

class A {
   const test = 4;
}

class B {

  private $a = null;
  public function __construct(){
      $this->$a = new A();
  }

  public function show(){
     echo $this->$a::test;
  }

}

$b = new B();
$b->show();

How to calling static variable test in class A? Thanks in advance


Solution

  • Every thing is fine except $this->$a::test; and $this->$a = new A();. You have to use property without $ sign like below

    class A {
       const test = 4;
    }
    
    class B {
    
      private $a = null;
    
      public function __construct()
      {
          $this->a = new A();
      }
    
      public function show()
      {
         echo $this->a::test;
      }
    }
    
    $b = new B();
    $b->show();