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

superjadex12 picture superjadex12 · Jul 16, 2009 · Viewed 13.6k times · Source

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 also refer to a class variable, a parent class variable, or a method from the parent class. There is no ambiguity in self::

Is self:: depreciated and/or are there any caveats or cons to using this style?

I understand that self:: and parent:: refer to a static instance of the class, but in kohana, unless you specifically define a method as static, there does not seem to be a difference.

Thanks.

Added an example: Assuming this application stores forums from multiple websites...

class Forum_Controller extends Controller {

    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        echo self::categories();
    }

/*
 * get a list of categories from a specific site.
 */
    private function categories()
    {
        $db = new Database;
        $categories = $db->query("
            SELECT * FROM
            forum_categories
            WHERE fk_site = '$this->site_id'
        ");
        $view = new View('categories_view');
        $view->categories = $categories;
        return $view;
    }

}

This examples works in kohana with error reporting set to: error_reporting(E_ALL & ~E_STRICT);

$this->site_id is defined in the main Controller_Core class (a library in kohana).

As far as I know, $this is not supposed to be available since I am calling self::categories() in a static manner, but it is only when i define categories() as static that it throws an error.

But as I said I much rather prefer using self:: because from a readability perspective, I know exactly where this function should be, rather than using $this which causes ambiguity, to me that is.

Answer

benlumley picture benlumley · Jul 16, 2009

There is a difference.

$this refers to an instance of an object.

parent and self are used to call methods statically.

This page of PHP's manual explains it in better detail than I have time to write at the moment. The first example in particular should help to highlight some of the differences. I encourage you to copy paste the first example and mess about with it, as I think its an important concept to get in your mind if you don't already know the difference.