I'm noob in PHP, help me please, why it dosen't echo values from my class? Maybe in PHP work with values in class is going by the specific way (I came from Java/C#) ?
<?php
class GuestBook
{
private static $numInstances = 0;
private $var1 = 10;
function __construct()
{
$numInstances++;
}
public static function getNumInstances()
{
return $numInstances;
}
public function getVar1()
{
return $var1;
}
}
$instance1 = new GuestBook();
$instance2 = new GuestBook();
echo(GuestBook::getNumInstances());
echo($instance1->getVar1());
?>
Change your class to:
class GuestBook
{
private static $numInstances = 0;
private $var1 = 10;
function __construct()
{
static::$numInstances++;
}
public static function getNumInstances()
{
return static::$numInstances;
}
public function getVar1()
{
return $this->var1;
}
}
Will output:
210
Hope this helps.
<?php
class GuestBook
{
private static $numInstances = 0;
private static $var1 = 10;
function __construct()
{
static::$numInstances++;
}
public static function getNumInstances()
{
return GuestBook::$numInstances;
}
public function getVar1()
{
return GuestBook::var1;
}
}
$instance1 = new GuestBook();
$instance2 = new GuestBook();
echo(GuestBook::getNumInstances());
?>
you need to access the static variables using class name instead of object name
you need to use -> for non static methods