4
<?php
class Foo{
protected $calc;
function __construct(){
$this->calc = 2;
}
public static function getCalc(){
return $this->calc * 5;
}
}
Foo::getCalc();
When I spin, he gives me that mistake:
Fatal error: Using $this when not in Object context in...
Why can’t I call a variable protected
within a function defined as static?
Because the variable does not exist in the static scope. Understand that nonstatic variables only come into existence when the class object is created, hence the error. To use the variable, VC first needs to create a Foo object.
– user28595
The problem is not protected but the fact that you manipulate an instance attribute in a static method, it belongs to the class and not to the object, then access it to the
$this
is not valid.– rray
Right, and what would be the solution to that? Change statics to public?
– Daniel Swater
This code seems to be an example just ... doesn’t it do much ... the purpose of the method being static is to save the creation of an object? can solve this with a fixed value or a constant.
– rray