简体   繁体   中英

Use function and static method

In a table class I want to use simple functions but also static functions, how can I do? Here is my current code (which does not work)

In my controller, I just want to do: Table::get('posts') which directly invokes the function check_table($table) .

<?php
namespace Fwk\ORM;
use Fwk\Application;
use Fwk\Database\Database;

class Table extends Application {

    public function __construct()
    {
        $this->db = new Database();
    }

    public static function get($table) {
        if($this->check_table($table)) {
            return "ok";
        }

    }
    public function check_table($table) {
        $r = $this->$db->query("SELECT 1 FROM $table");
        return $r;
    }

}
?>

You have to understand exactly what static means. When you declare a method as static, you're essentially saying "This method can be called directly without actually instantiating it's class". So while you're in a static method, you won't have access to $this since you're not in object context.

You could make check_table() static also and use it as a sort of factory:

public static function get($table) {
    if(self::check_table($table)) {
        return "ok";
    }

}
public static function check_table($table) {
    $r = (new Database())->query("SELECT 1 FROM $table");
    return $r;
}

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

你可以尝试把“self::MethodeName”而不是“this->MethodeName”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM