Using $this, self::, parent:: for code readability

前端 未结 6 693
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 13:51

I would like to know if it is acceptable/preferred to use self::method() and parent::method() when working in php classes.

You can use $this->method() but $this-> can al

6条回答
  •  隐瞒了意图╮
    2021-02-08 14:07

    I couldn't add a comment (apparently i do not have the required rep!)

    class Forum_Controller extends Controller {
    
    public function __construct()
    {
        parent::__construct();
    }
    
    public function index()
    {
        echo self::categories();
    }
    
    /*
     * get a list of categories from a specific site.
     */
    private static function categories()
    {
        $db = new Database;
    
        // You cannot use $this in a static function, because static functions are per class 
        // and not per object it doesnt know what $this is :)   (make private static $site_id and use self::$site_id) if this is what you want
    
        $categories = $db->query("
                SELECT * FROM
                forum_categories
                WHERE fk_site = '$this->site_id'
        ");
        $view = new View('categories_view');
        $view->categories = $categories;
        return $view;
    }
    

    }

    Like i said, you should use error_reporting(E_ALL | E_STRICT); (change it in the kohana file )

    calling private function categories() statically works due to a bug in PHP, you shouldn't be able to do it :)

提交回复
热议问题