Jump to content

Struggling to understand the differences between "self", "$this", "::" and "->" and when / how to use them


timothyarden

Recommended Posts

Hi Everyone,
I am Struggling to understand the differences between "self", "$this", "::" and "->" and when / how to use them in classes. Any help would be appreciated, also if you could dumb it down to plain english that would help alot! Thanks in advance :)

(In what I've been reading it's been saying stuff about static methods stuff and I'm not sure when / how this influences it - am I going down the wrong path?)

Hi,

 

it's really simple: $this refers to the current object, and self refers to the current classThe -> operator is used to call a method or access an attribute of an object. And :: is used to access a static method or attribute of a class.

<?php

class A
{
	public static $stat = 'Some static attribute';
	
	public $inst = 'Some attribute of the instance';

	public function test()
	{
		var_dump(self::$stat);    // self refers to the class A
		var_dump($this->inst);    // $this refers to the specific instance of A
	}
}

$a = new A();
$a->test();

There are some gotchas as to how self behaves in subclasses, but you should get the basic idea.

Thankyou for your post Jacques. 

Could you also explain what you mean by current object? (I understand current class). // I tried to look up objects but it didnt help http://www.php.net/manual/en/language.types.object.php 

Could you also explain what a method or attribute of an object is? 

"The -> operator is used to call a method or access an attribute of an object"; does this mean it can also be used in addition to :: to access static methods or an attribute of a class or is :: to be used exclusively for static methods and attributes of classes?
 

Also from your previous code will this code extract

 

var_dump(self::$stat); // self refers to the class A
var_dump($this->inst); // $this refers to the specific instance of A

have the same effect as

 

var_dump($this::$stat); // self refers to the class A
var_dump(self->inst); // $this refers to the specific instance of A
or have I missed the point

You've missed the point. It's generally somewhat pointless to talk about details like this when you're not familiar with basics like objects, attributes and methods.

 

There are many introductions for object-oriented PHP. You should start there. The first page I came accross is this one.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.