2016-05-16 71 views
0

我目前正在構建一個種類的 MVC PHP應用程序,以更好地理解MVC開發方法,但是我提出了一個問題。在PHP類上調用私有函數

我的模型類

<?php 
//My super awesome model class for handling posts :D 
class PostsMaster{ 
    public $title; 
    public $content; 
    public $datePublished; 
    public $dateEdited; 

    private function __constructor($title, $content, $datePublished, $dateEdited){ 
     $this->title = $title; 
     $this->content = $content; 
     $this->datePublished = $datePublished; 
     $this->dateEdited = $dateEdited; 
    } 

    private $something = 'eyey78425'; 

    public static function listPost(){ 
     $postList = []; 
     //Query all posts 
     $DBQuery = DB::getInstance($this->something);//Database PDO class :D 
     $DBQuery->query('SELECT * FROM Posts'); 
     foreach($DBQuery as $post){ 
      $postList[] = new PostsMaster($post['postTitle'], $post['postContent'], $this->formatDate($post['datePub']), $this->formatDate($post['dateEdit'])); 
     } 
     return $postList; 
    } 

    private function formatDate($unformattedDate){ 
     /* Formatting process */ 
     return $formattedDate; 
    } 
} 

我怎麼叫它控制器

<?php 

require 'index.php'; 

function postList(){ 
    require 'views/postList.php'; 
    PostsMaster::listPost(); 
} 

上,但是當渲染我得到這個錯誤:

fatal error using $this when not in object context... 

我不打算讓公共formatDate函數,因爲我不希望它被調用外,但我怎麼能在我的代碼中正確調用它?

+0

當你有一個'static'方法不能使用'this' - >'$這個 - > formatDate'使'formatDate'靜態和使用'自:: formatDate' –

+0

您所呼叫的方法靜態'PostsMaster :: listPost();',這意味着該類沒有實例化,這反過來意味着'__construct'沒有被調用,'$ this'不可用。關於你的問題,你通常希望公開構造函數,並且可能有一些私有方法。但具有私有性質和方法的原因是讓他們在課堂外不可用。這意味着你將不被允許從你的控制器調用私有方法。 – JimL

+0

@JimL是的,我不想讓$ var = new PostsMaster();因爲這會打開一個到API的額外連接,並且我的通話受到限制。 (不包括在我的例子中,但是在構造函數中),所以我緩存回調並將其保存到私有變量中。我不知道是否有另外一種方法可以做到這一點 –

回答

0

問題出在您將「this」(一個對象限定符)用於靜態方法的事實。

相反,您應該使用靜態限定符self

public static function listPost(){ 
     $postList = []; 
     //Query all posts 
     $DBQuery = DB::getInstance(self::something);//Database PDO class :D 
     $DBQuery->query('SELECT * FROM Posts'); 
     foreach($DBQuery as $post){ 
      $postList[] = new PostsMaster($post['postTitle'], $post['postContent'], $this->formatDate($post['datePub']), $this->formatDate($post['dateEdit'])); 
     } 
     return $postList; 
    } 
+0

自我也適用於私人功能? –

+0

是的,它肯定是 – zoubida13

+0

@Forcefield self是$ this的靜態equivialent。因此可以調用類屬性和方法(不管可見性)。 – JimL