self and $this usage

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View


Is it possible to do without $this?

I have got an instance of another class inside a class. Now I want to access
this classes functions using the self keyword, but it seems i cant.

Or can I?

Like, self::$nexgen->Function?

Or do I have to use the $this keyword. Having both keywords seems pointless
to me, i'd like to stick with one...

Maybe im getting confused.

Re: self and $this usage

Basically, self:: and $this apply to class that you are currently in.
So, if you have class A and it has a member variable that is an
instance of class B, self:: and $this refer to class A.  To access
variables and functions of class B, the rules apply as they would
anywhere else.  For instance:

Class A {
    const someConst = 1;
    var $b; //will be an instance of class B

    function A() { //the constructor for class A
        $b = new B();

    function myFunc() {  //execute some method in class B

    static function myStaticFunc() {
        echo "Hello!";

The difference between $this and self:: is as follows: use $this to
refer to class member variables and non-static methods.  Use self:: to
refer to constants and static methods.  The reason is that constants
and static methods don't require instantiation of an object, so $this
wouldn't exist (since $this refers to an instance of an object).  So,
in the above example, to call myStaticFunc() from within class A, you
would write self::myStaticFunc().  Likewise, to use the constant
someConst, you would write self::someConst.  To call myStaticFunc() or
use someConst from somewhere else (i.e. in a script or from some other
class), you would write A::myStaticFunc() or A::someConst (note that
it's 'A' and not the name of a variable that refers to an instance of
class A).

Re: self and $this usage

ZeldorBlat wrote:

Quoted text here. Click to load it

I thought self refers the class of the the current object while $this refers
to the instance.

See also


Site Timeline