Call protected variable within static method

3
<?php

     class Foo{

          protected $calc;

          function __construct(){
               $this->calc = 2;
          }

          public static function getCalc(){
               return $this->calc * 5;
          }
     }
     Foo::getCalc();

When I squeeze, it gives me this error:

  

Fatal error: Using $ this when not in object context in ...

Why can not I call a protected variable within a function defined as static?

    
asked by anonymous 15.02.2016 / 17:09

2 answers

4

Think of all static members as a single instance pre-instantiated in the application. It's as if these members belong to another object.

Instance members are each considered to belong to their own instance (it can be a variable). There is no way to mix them. In the background are very different things, in different memory locations with different roles.

Even if you try, what $this are we talking about? This is a variable that saves the instance, the language does not know what object is speaking in the code, after all there is accessing something that is not of any normal instance.

    
15.02.2016 / 17:18
0

Can not access class attributes or other methods within a static method. Static methods are not in the context of the object.

    
24.08.2016 / 19:39