That's the problem, how can I call a class variable from a class function? Let me explain better:
<?php
class Mine
{
private $g = 'gg';
const COSTANTE = 'valo';
public static function sayHello()
{
echo self::COSTANTE;
echo '<br>';
echo $this->g;
}
}
$h = new Mine();
$h->sayHello();
$h::sayHello();
?>
when I run this, it just print the constant COSTANTE.... Why it doesn't print the variable g?
Turn on error reporting ( error_reporting ( E_ALL ); ), and you should receive the following error:
Fatal error: Using $this when not in object context
The pseudo-variable $this
is a reference to the calling object, and is available from within an object context.
self
is used to access the current class, since static functions can be called without the actual object instance, when the method is called statically $this
reference does not exists.
A method declared as static
can be accessed with an instantiated class object ( but it is always executed in a static context ), a property declared as static
cannot.
valo
will be printed but gg
and will not. The issue is because you have used a non-static variable in a static method which will raise a FATAL error and will stop execution. This is because there is no object context.
Its not encouraged to use non-static variable inside static methods but, in case you need to use one, you have to create an object first.
Your sayHello
function will be something like
public static function sayHello()
{
echo self::COSTANTE;
echo '<br>';
$mineObject = new Mine;
echo $mineObject->g;
}
I will also suggest keep error reporting and display errors ON while developing so that you can have a better idea of whats happening out there.
error_reporting(E_ALL);
ini_set('display_errors', 'ON');