2

This is my Code:

class content
{
    public $text;
    public static $total;

    function __construct($content){
        $this->text = $content;
        $this->total = 0;
    }

    public static function vote(){
        self::$total++;
    }

}


$foo = new content("hai");
echo "<pre>";
print_r($foo);
echo "</pre>";

$foo::vote();

echo "<pre>";
print_r($foo);
echo "</pre>";

The output:


Strict Standards: Accessing static property content::$total as non static in C:\Users\jodi\Documents\Visual Studio 2013\Projects\FinalProject\FinalProject\index.php on line 10

content Object
(
    [text] => hai
    [total] => 0
)
content Object
(
    [text] => hai
    [total] => 0
)

the $total is not change. and got error. -,-

How to increment $total?

is there any alternative way??

2
  • You did reference the variable $total in the constructor as an object variable but you've declared it to be a class variable. Why is the method vote() declared as a class method?
    – Havelock
    Nov 3, 2014 at 5:38
  • Remove $this->total = 0; from constructor. Nov 3, 2014 at 5:42

1 Answer 1

5

The problem comes from referencing the variable $total as object variable in the constructor, since you've declared it as static, that is a class variable.
Since I don't know the idea behind your design you have (at least) two options:
Option 1:
If you need $total as a class variable, remove the initialisation from the constructor. You could define a default value 0 and use an object method to get the value of the class variable, i.e.

class content
{
    public $text;
    public static $total = 0;

    function __construct($content){
        $this->text = $content;
    }

    public function getTotal() {
        return self::$total;
    }

    public static function vote(){
        self::$total++;
    }

}

Option 2:
If you don't really need it as a class variable, but a field which is different for each object you instantiate, get rid of the static and declare the vote() method as object method:

class content
{
    public $text;
    public $total;

    function __construct($content){
        $this->text = $content;
        $this->total = 0;
    }

    public function vote(){
        $this->total++;
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy