Statyczna metoda nie zwraca wartości

0

Mam problem, statyczna metoda nie zwraca statycznej zmiennej.

index.php

$p1 = new Post(1);
$p2 = new Post(2);
echo Post::getCounter()."<hr>";

class.php

<?php
class Post{
	public static $counter=0;
	public static $db; 
	
	
	
	private $id;
	
	private $title;
	private $content;
	
	public function __construct($id){
		$db = new PDO('sqlite:SimplestCMS.db') or die("Can't open db!");

			$res = $db->query("SELECT * FROM Posts WHERE ID=".$id);
			$row = $res->fetch(PDO::FETCH_ASSOC);
				$this->title = $row['Title'];
				$this->content = $row['Content'];
				
			
			
			
	}
	
	public function get($varName){
            return $this->$varName;
    }
	
	public function getCounter(){
			return self::$counter;
	}
	
	public function getEverything(){
			return array($this->id,$this->title,$this->content);
	}
}

dokładniej to nie dizała metoda getCounter().

1

Metodę w ten sposób:

echo Post::getCounter();

można wywołać gdy jest ona statyczna.
Więc musisz zmienić:

    public function getCounter(){
            return self::$counter;
    }

na

    public static function getCounter(){
            return self::$counter;
    }

aby błędami nie sypało.

http://php.net/manual/en/language.oop5.static.php

2

A nie wystarczy:

<?php
class Post{
	static $counter=0;
}

echo Post::$counter;

1 użytkowników online, w tym zalogowanych: 0, gości: 1