在PHP类上调用私有函数

在PHP类上调用私有函数

问题描述:

我目前正在构建一个种类的 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的额外连接,并且我的通话受到限制。 (不包括在我的例子中,但是在构造函数中),所以我缓存回调并将其保存到私有变量中。我不知道是否有另外一种方法可以做到这一点 –

问题出在您将“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