Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dk4210's avatar

Host to access a variable in static method

Hello guys,

if I have something like this

class test
{

      public function __construct()

    {

    $var = 123;

    }

      public static method mytest()

      {

      // How do I access the $var from the construct?


      }


}

I'm trying to figure out how to share the variables in the same class among methods. I have the hardest problem understanding this concept.

Thanks!

0 likes
10 replies
Sinnbeck's avatar

Unsure why you would (use dynamic methods instead), but try this :)

class test
{
      protected $var;
      public function __construct()

    {

    $this->var = 123;

    }

      public static method mytest()

      {
         $self = new static; //OBJECT INSTANTIATION
        $var = $self->var;
      // How do I access the $var from the construct?


      }


}
1 like
Snapey's avatar

how does this relate to your original question?

dk4210's avatar

Actually, its related due to this is my actual code. I'm not sure if due to the Variable that I'm trying to pass inside the method.

dk4210's avatar

I did change it from the static method.

hasan_dev's avatar

Just using a simple keyword to access protected/private variable from a static method.

class test {

  public function __construct()

{

$var = 123;

}

  public static method mytest()

  {
			//Easy way
			self::$var

  }

}

martinbean's avatar

@hasan_dev Why have you signed up just to reply to a thread that’s almost half a decade old? 🤷‍♂️

Please or to participate in this conversation.