在PHP类上调用私有函数

时间:2016-05-16 16:14:27

标签: php

我目前正在构建一个类型的 MVC PHP应用程序来理解更好的MVC开发方法,但我提出了一个问题。

我的模特课

<?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函数,因为我不想在外面调用它,但我怎么能在我的代码中正确调用它?

1 个答案:

答案 0 :(得分:0)

问题来自于你使用&#34;这个&#34; (一个对象限定符)到一个静态方法。

相反,您应该使用静态限定符 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;
    }