SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Nov 2006
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    $this->methodname() vs. self::methodname()

    Is there any difference in calling a method of the current class by using $this->methodname() vs. self::methodname()?

  2. #2
    SitePoint Member MrMe's Avatar
    Join Date
    Jan 2007
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    self must be used to access static methods. It also ensures that the method is called on the current class.

  3. #3
    SitePoint Addict
    Join Date
    Nov 2005
    Location
    Germany
    Posts
    235
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    To extend this a little: MyClass::method() is bound "statically" to the class which means that no instance has to be created with new MyClass before using it, this is called class method or class property. This also means that all instances of a class share the same static properties.
    $this operates on an instance of the class.

  4. #4
    SitePoint Member
    Join Date
    Nov 2006
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have discovered that self::method() and $this->method() work practically the same:
    Quote Originally Posted by http://www.php.net/manual/en/language.oop5.static.php
    If the call is done by self then self is translated to the current class, that is the class the code belongs to. Here also no inheritance rules apply.
    ... but there is a little exception: because when you call a method statically, outside of the class, you cannot access $this, not even indirectly:
    PHP Code:
    <?php
    class {
        static 
    $v 'value';
        function 
    get_v() {
            return 
    self::$v;
        }
        function 
    get2() {
            return 
    $this->v;
        }
        function 
    doit() {
            echo 
    'self is ' self::get_v()  . '<br>';
            echo 
    'this is ' $this->get_v()  . '<br>';
        }
    }

    $o = new c;

    echo 
    '<br><b>non-static func:</b><br>';
    $o->doit();

    echo 
    '<br><b>static func:</b><br>';
    c::doit();
    ?>
    gives this:
    Code:
    non-static func:
    self is value
    this is value
    
    static func:
    self is value
    
    Fatal error: Using $this when not in object context in [...]


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •