Help understanding PHP5 error

2020-05-01 01:38发布

问题:

In short.. question is... "Say what?" To expand... "I don't get the error"

Strict Standards: Non-static method Pyro\Template::preLoad() should not be called statically, assuming $this from incompatible context in /opt/lampp/htdocs/dc/pyro/app/controllers/admin/courses.php on line 14

public function actionIndex() {
    $this->data->users = $this->DB->query("SELECT id, name, description FROM :@courses")->getAll();
    $this->data->title = 'Courses';
    $this->data->content_area = \Pyro\Template::preLoad('admin/courses/index', $this->data); // Line 14
}

Template... its incomplete...

<?php
namespace Pyro;

class Template {

    // Stores default master template
    public static $defaultTemplate = 'template.php';

    public function preLoad($template, $page) {
        ob_start();

        include( VIEWS . "{$template}.php");

        $buffer = ob_get_contents();
        @ob_end_clean();
        return $buffer;
    }

    public function load($page) {
        include( VIEWS . self::$defaultTemplate);
    }
}

Why does this error appear? Cheers

回答1:

Well the preLoad function is not static. Which means only an object of the class Template can use this method. A static method exists indepedently of any object of the class.

Template::preLoad is a static call : you didn't create a Template object, then call the preLoad method. So basically, you've got two solutions :

  • Making preLoad static;
  • Creating a Template object, and then call its preLoad function.


回答2:

preLoad function should be static

public static function preLoad($template, $page) {


回答3:

preLoad function isn't static. ti should look like this:

public static function preLoad($template, $page) {
        ob_start();

        include( VIEWS . "{$template}.php");

        $buffer = ob_get_contents();
        @ob_end_clean();
        return $buffer;
    }


回答4:

Like everyone said, the you called the function with as a static method:

Template::preLoad(xxx)

The :: means static in PHP. Functions are typically called as static :: or object -> calls.

The function definition is one or the other:

public static function preLoad($template, $page)

Called like: Template::preLoad('admin/courses/index', $this->data);

OR

public function preLoad($template, $page)

Called like Template->preLoad('admin/courses/index', $this->data);

For reference, a static function is able to be called without instantiating an object. If your function doesn't need an object to run, you could make it static. Basically, this means you can't reference $this in a static method. It will run with the given inputs without having to construct the object.