Anthony Gorshenin Anthony Gorshenin - 1 year ago 69
PHP Question

Echoing values from class PHP

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());


?>

Answer Source

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.