By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,934 Members | 1,528 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,934 IT Pros & Developers. It's quick & easy.

self and $this usage

P: n/a

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.
Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies

P: n/a
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).

Jul 17 '05 #2

P: n/a
ZeldorBlat wrote:
Basically, self:: and $this apply to class that you are currently in.

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

See also

Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.