What does the variable $this mean in PHP? - php

I see the variable $this in PHP all the time and I have no idea what it's used for. I've never personally used it.
Can someone tell me how the variable $this works in PHP?

It's a reference to the current object, it's most commonly used in object oriented code.
Reference: http://www.php.net/manual/en/language.oop5.basic.php
Primer: http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html
Example:
<?php
class Person {
public $name;
function __construct( $name ) {
$this->name = $name;
}
};
$jack = new Person('Jack');
echo $jack->name;
This stores the 'Jack' string as a property of the object created.

The best way to learn about the $this variable in PHP is to try it against the interpreter in various contexts:
print isset($this); //true, $this exists
print gettype($this); //Object, $this is an object
print is_array($this); //false, $this isn't an array
print get_object_vars($this); //true, $this's variables are an array
print is_object($this); //true, $this is still an object
print get_class($this); //YourProject\YourFile\YourClass
print get_parent_class($this); //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this); //delicious data dump of $this
print $this->yourvariable //access $this variable with ->
So the $this pseudo-variable has the Current Object's method's and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:
Class Dog{
public $my_member_variable; //member variable
function normal_method_inside_Dog() { //member method
//Assign data to member variable from inside the member method
$this->my_member_variable = "whatever";
//Get data from member variable from inside the member method.
print $this->my_member_variable;
}
}
$this is reference to a PHP Object that was created by the interpreter for you, that contains an array of variables.
If you call $this inside a normal method in a normal class, $this returns the Object (the class) to which that method belongs.
It's possible for $this to be undefined if the context has no parent Object.
php.net has a big page talking about PHP object oriented programming and how $this behaves depending on context.
https://www.php.net/manual/en/language.oop5.basic.php

I know its old question, anyway another exact explanation about $this. $this is mainly used to refer properties of a class.
Example:
Class A
{
public $myname; //this is a member variable of this class
function callme() {
$myname = 'function variable';
$this->myname = 'Member variable';
echo $myname; //prints function variable
echo $this->myname; //prints member variable
}
}
output:
function variable
member variable

It is the way to reference an instance of a class from within itself, the same as many other object oriented languages.
From the PHP docs:
The pseudo-variable $this is available
when a method is called from within an
object context. $this is a reference
to the calling object (usually the
object to which the method belongs,
but possibly another object, if the
method is called statically from the
context of a secondary object).

Lets see what happens if we won't use $this and try to have instance variables and
constructor arguments with the same name with the following code snippet
<?php
class Student {
public $name;
function __construct( $name ) {
$name = $name;
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
It echos nothing but
<?php
class Student {
public $name;
function __construct( $name ) {
$this->name = $name; // Using 'this' to access the student's name
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
this echoes 'Tom'

when you create a class you have (in many cases) instance variables and methods (aka. functions). $this accesses those instance variables so that your functions can take those variables and do what they need to do whatever you want with them.
another version of meder's example:
class Person {
protected $name; //can't be accessed from outside the class
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
// this line creates an instance of the class Person setting "Jack" as $name.
// __construct() gets executed when you declare it within the class.
$jack = new Person("Jack");
echo $jack->getName();
Output:
Jack

This is long detailed explanation. I hope this will help the beginners. I will make it very simple.
First, let's create a class
<?php
class Class1
{
}
You can omit the php closing tag ?> if you are using php code only.
Now let's add properties and a method inside Class1.
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
return "I am Method 1";
}
}
The property is just a simple variable , but we give it the name property cuz its inside a class.
The method is just a simple function , but we say method cuz its also inside a class.
The public keyword mean that the method or a property can be accessed anywhere in the script.
Now, how we can use the properties and the method inside Class1 ?
The answer is creating an instance or an object, think of an object as a copy of the class.
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
return "I am Method 1";
}
}
$object1 = new Class1;
var_dump($object1);
We created an object, which is $object1 , which is a copy of Class1 with all its contents. And we dumped all the contents of $object1 using var_dump() .
This will give you
object(Class1)#1 (2) { ["property1"]=> string(15) "I am property 1" ["property2"]=> string(15) "I am property 2" }
So all the contents of Class1 are in $object1 , except Method1 , i don't know why methods doesn't show while dumping objects.
Now what if we want to access $property1 only. Its simple , we do var_dump($object1->property1); , we just added ->property1 , we pointed to it.
we can also access Method1() , we do var_dump($object1->Method1());.
Now suppose i want to access $property1 from inside Method1() , i will do this
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
$object2 = new Class1;
return $object2->property1;
}
}
$object1 = new Class1;
var_dump($object1->Method1());
we created $object2 = new Class1; which is a new copy of Class1 or we can say an instance. Then we pointed to property1 from $object2
return $object2->property1;
This will print string(15) "I am property 1" in the browser.
Now instead of doing this inside Method1()
$object2 = new Class1;
return $object2->property1;
We do this
return $this->property1;
The $this object is used inside the class to refer to the class itself.
It is an alternative for creating new object and then returning it like this
$object2 = new Class1;
return $object2->property1;
Another example
<?php
class Class1
{
public $property1 = 119;
public $property2 = 666;
public $result;
public function Method1()
{
$this->result = $this->property1 + $this->property2;
return $this->result;
}
}
$object1 = new Class1;
var_dump($object1->Method1());
We created 2 properties containing integers and then we added them and put the result in $this->result.
Do not forget that
$this->property1 = $property1 = 119
they have that same value .. etc
I hope that explains the idea.
This series of videos will help you a lot in OOP
https://www.youtube.com/playlist?list=PLe30vg_FG4OSEHH6bRF8FrA7wmoAMUZLv

$this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

$this is a special variable and it refers to the same object ie. itself.
it actually refer instance of current class
here is an example which will clear the above statement
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>

It refers to the instance of the current class, as meder said.
See the PHP Docs. It's explained under the first example.

Generally, this keyword is used inside a class, generally with in the member functions to access non-static members of a class(variables or functions) for the current object.
this keyword should be preceded with a $ symbol.
In case of this operator, we use the -> symbol.
Whereas, $this will refer the member variables and function for a particular instance.
Let's take an example to understand the usage of $this.
<?php
class Hero {
// first name of hero
private $name;
// public function to set value for name (setter method)
public function setName($name) {
$this->name = $name;
}
// public function to get value of name (getter method)
public function getName() {
return $this->name;
}
}
// creating class object
$stark = new Hero();
// calling the public function to set fname
$stark->setName("IRON MAN");
// getting the value of the name variable
echo "I Am " . $stark->getName();
?>
OUTPUT:
I am IRON MAN
NOTE:
A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created.

Related

PHP $this keyword in Inheritance [duplicate]

In PHP 5, what is the difference between using self and $this?
When is each appropriate?
Short Answer
Use $this to refer to the current
object. Use self to refer to the
current class. In other words, use
$this->member for non-static members,
use self::$member for static members.
Full Answer
Here is an example of correct usage of $this and self for non-static and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
Here is an example of incorrect usage of $this and self for non-static and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo self::$non_static_member . ' '
. $this->static_member;
}
}
new X();
?>
Here is an example of polymorphism with $this for member functions:
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
$this->foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
Here is an example of suppressing polymorphic behaviour by using self for member functions:
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
self::foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.
From http://www.phpbuilder.com/board/showthread.php?t=10354489:
By http://board.phpbuilder.com/member.php?145249-laserlight
The keyword self does NOT refer merely to the 'current class', at least not in a way that restricts you to static members. Within the context of a non-static member, self also provides a way of bypassing the vtable (see wiki on vtable) for the current object. Just as you can use parent::methodName() to call the parents version of a function, so you can call self::methodName() to call the current classes implementation of a method.
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function getTitle() {
return $this->getName()." the person";
}
public function sayHello() {
echo "Hello, I'm ".$this->getTitle()."<br/>";
}
public function sayGoodbye() {
echo "Goodbye from ".self::getTitle()."<br/>";
}
}
class Geek extends Person {
public function __construct($name) {
parent::__construct($name);
}
public function getTitle() {
return $this->getName()." the geek";
}
}
$geekObj = new Geek("Ludwig");
$geekObj->sayHello();
$geekObj->sayGoodbye();
This will output:
Hello, I'm Ludwig the geek
Goodbye from Ludwig the person
sayHello() uses the $this pointer, so the vtable is invoked to call Geek::getTitle().
sayGoodbye() uses self::getTitle(), so the vtable is not used, and Person::getTitle() is called. In both cases, we are dealing with the method of an instantiated object, and have access to the $this pointer within the called functions.
Do not use self::. Use static::*
There is another aspect of self:: that is worth mentioning. Annoyingly, self:: refers to the scope at the point of definition, not at the point of execution. Consider this simple class with two methods:
class Person
{
public static function status()
{
self::getStatus();
}
protected static function getStatus()
{
echo "Person is alive";
}
}
If we call Person::status() we will see "Person is alive" . Now consider what happens when we make a class that inherits from this:
class Deceased extends Person
{
protected static function getStatus()
{
echo "Person is deceased";
}
}
Calling Deceased::status() we would expect to see "Person is deceased". However, we see "Person is alive" as the scope contains the original method definition when the call to self::getStatus() was defined.
PHP 5.3 has a solution. The static:: resolution operator implements "late static binding" which is a fancy way of saying that it's bound to the scope of the class called. Change the line in status() to static::getStatus() and the results are what you would expect. In older versions of PHP you will have to find a kludge to do this.
See PHP Documentation
So to answer the question not as asked...
$this-> refers to the current object (an instance of a class), whereas static:: refers to a class.
To really understand what we're talking about when we talk about self versus $this, we need to actually dig into what's going on at a conceptual and a practical level. I don't really feel any of the answers do this appropriately, so here's my attempt.
Let's start off by talking about what a class and an object is.
Classes And Objects, Conceptually
So, what is a class? A lot of people define it as a blueprint or a template for an object. In fact, you can read more About Classes In PHP Here. And to some extent that's what it really is. Let's look at a class:
class Person {
public $name = 'my name';
public function sayHello() {
echo "Hello";
}
}
As you can tell, there is a property on that class called $name and a method (function) called sayHello().
It's very important to note that the class is a static structure. Which means that the class Person, once defined, is always the same everywhere you look at it.
An object on the other hand is what's called an instance of a Class. What that means is that we take the "blueprint" of the class, and use it to make a dynamic copy. This copy is now specifically tied to the variable it's stored in. Therefore, any changes to an instance is local to that instance.
$bob = new Person;
$adam = new Person;
$bob->name = 'Bob';
echo $adam->name; // "my name"
We create new instances of a class using the new operator.
Therefore, we say that a Class is a global structure, and an Object is a local structure. Don't worry about that funny -> syntax, we're going to go into that in a little bit.
One other thing we should talk about, is that we can check if an instance is an instanceof a particular class: $bob instanceof Person which returns a boolean if the $bob instance was made using the Person class, or a child of Person.
Defining State
So let's dig a bit into what a class actually contains. There are 5 types of "things" that a class contains:
Properties - Think of these as variables that each instance will contain.
class Foo {
public $bar = 1;
}
Static Properties - Think of these as variables that are shared at the class level. Meaning that they are never copied by each instance.
class Foo {
public static $bar = 1;
}
Methods - These are functions which each instance will contain (and operate on instances).
class Foo {
public function bar() {}
}
Static Methods - These are functions which are shared across the entire class. They do not operate on instances, but instead on the static properties only.
class Foo {
public static function bar() {}
}
Constants - Class resolved constants. Not going any deeper here, but adding for completeness:
class Foo {
const BAR = 1;
}
So basically, we're storing information on the class and object container using "hints" about static which identify whether the information is shared (and hence static) or not (and hence dynamic).
State and Methods
Inside of a method, an object's instance is represented by the $this variable. The current state of that object is there, and mutating (changing) any property will result in a change to that instance (but not others).
If a method is called statically, the $this variable is not defined. This is because there's no instance associated with a static call.
The interesting thing here is how static calls are made. So let's talk about how we access the state:
Accessing State
So now that we have stored that state, we need to access it. This can get a bit tricky (or way more than a bit), so let's split this into two viewpoints: from outside of an instance/class (say from a normal function call, or from the global scope), and inside of an instance/class (from within a method on the object).
From Outside Of An Instance/Class
From the outside of an instance/class, our rules are quite simple and predictable. We have two operators, and each tells us immediately if we're dealing with an instance or a class static:
-> - object-operator - This is always used when we're accessing an instance.
$bob = new Person;
echo $bob->name;
It's important to note that calling Person->foo does not make sense (since Person is a class, not an instance). Therefore, that is a parse error.
:: - scope-resolution-operator - This is always used to access a Class static property or method.
echo Foo::bar()
Additionally, we can call a static method on an object in the same way:
echo $foo::bar()
It's extremely important to note that when we do this from outside, the object's instance is hidden from the bar() method. Meaning that it's the exact same as running:
$class = get_class($foo);
$class::bar();
Therefore, $this is not defined in the static call.
From Inside Of An Instance/Class
Things change a bit here. The same operators are used, but their meaning becomes significantly blurred.
The object-operator -> is still used to make calls to the object's instance state.
class Foo {
public $a = 1;
public function bar() {
return $this->a;
}
}
Calling the bar() method on $foo (an instance of Foo) using the object-operator: $foo->bar() will result in the instance's version of $a.
So that's how we expect.
The meaning of the :: operator though changes. It depends on the context of the call to the current function:
Within a static context
Within a static context, any calls made using :: will also be static. Let's look at an example:
class Foo {
public function bar() {
return Foo::baz();
}
public function baz() {
return isset($this);
}
}
Calling Foo::bar() will call the baz() method statically, and hence $this will not be populated. It's worth noting that in recent versions of PHP (5.3+) this will trigger an E_STRICT error, because we're calling non-static methods statically.
Within an instance context
Within an instance context on the other hand, calls made using :: depend on the receiver of the call (the method we're calling). If the method is defined as static, then it will use a static call. If it's not, it will forward the instance information.
So, looking at the above code, calling $foo->bar() will return true, since the "static" call happens inside of an instance context.
Make sense? Didn't think so. It's confusing.
Short-Cut Keywords
Because tying everything together using class names is rather dirty, PHP provides 3 basic "shortcut" keywords to make scope resolving easier.
self - This refers to the current class name. So self::baz() is the same as Foo::baz() within the Foo class (any method on it).
parent - This refers to the parent of the current class.
static - This refers to the called class. Thanks to inheritance, child classes can override methods and static properties. So calling them using static instead of a class name allows us to resolve where the call came from, rather than the current level.
Examples
The easiest way to understand this is to start looking at some examples. Let's pick a class:
class Person {
public static $number = 0;
public $id = 0;
public function __construct() {
self::$number++;
$this->id = self::$number;
}
public $name = "";
public function getName() {
return $this->name;
}
public function getId() {
return $this->id;
}
}
class Child extends Person {
public $age = 0;
public function __construct($age) {
$this->age = $age;
parent::__construct();
}
public function getName() {
return 'child: ' . parent::getName();
}
}
Now, we're also looking at inheritance here. Ignore for a moment that this is a bad object model, but let's look at what happens when we play with this:
$bob = new Person;
$bob->name = "Bob";
$adam = new Person;
$adam->name = "Adam";
$billy = new Child;
$billy->name = "Billy";
var_dump($bob->getId()); // 1
var_dump($adam->getId()); // 2
var_dump($billy->getId()); // 3
So the ID counter is shared across both instances and the children (because we're using self to access it. If we used static, we could override it in a child class).
var_dump($bob->getName()); // Bob
var_dump($adam->getName()); // Adam
var_dump($billy->getName()); // child: Billy
Note that we're executing the Person::getName() instance method every time. But we're using the parent::getName() to do it in one of the cases (the child case). This is what makes this approach powerful.
Word Of Caution #1
Note that the calling context is what determines if an instance is used. Therefore:
class Foo {
public function isFoo() {
return $this instanceof Foo;
}
}
Is not always true.
class Bar {
public function doSomething() {
return Foo::isFoo();
}
}
$b = new Bar;
var_dump($b->doSomething()); // bool(false)
Now it is really weird here. We're calling a different class, but the $this that gets passed to the Foo::isFoo() method is the instance of $bar.
This can cause all sorts of bugs and conceptual WTF-ery. So I'd highly suggest avoiding the :: operator from within instance methods on anything except those three virtual "short-cut" keywords (static, self, and parent).
Word Of Caution #2
Note that static methods and properties are shared by everyone. That makes them basically global variables. With all the same problems that come with globals. So I would be really hesitant to store information in static methods/properties unless you're comfortable with it being truly global.
Word Of Caution #3
In general you'll want to use what's known as Late-Static-Binding by using static instead of self. But note that they are not the same thing, so saying "always use static instead of self is really short-sighted. Instead, stop and think about the call you want to make and think if you want child classes to be able to override that static resolved call.
TL/DR
Too bad, go back and read it. It may be too long, but it's that long because this is a complex topic
TL/DR #2
Ok, fine. In short, self is used to reference the current class name within a class, where as $this refers to the current object instance. Note that self is a copy/paste short-cut. You can safely replace it with your class name, and it'll work fine. But $this is a dynamic variable that can't be determined ahead of time (and may not even be your class).
TL/DR #3
If the object-operator is used (->), then you always know you're dealing with an instance. If the scope-resolution-operator is used (::), you need more information about the context (are we in an object-context already? Are we outside of an object? etc).
self (not $self) refers to the type of class, whereas $this refers to the current instance of the class. self is for use in static member functions to allow you to access static member variables. $this is used in non-static member functions, and is a reference to the instance of the class on which the member function was called.
Because this is an object, you use it like: $this->member
Because self is not an object, it's basically a type that automatically refers to the current class. You use it like: self::member
$this-> is used to refer to a specific instance of a class's variables (member variables) or methods.
Example:
$derek = new Person();
$derek is now a specific instance of Person.
Every Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name
ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word "static" with "shared". Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).
Static Variables Example:
Pretend we have a database class with a single member variable: static $num_connections;
Now, put this in the constructor:
function __construct()
{
if(!isset $num_connections || $num_connections==null)
{
$num_connections=0;
}
else
{
$num_connections++;
}
}
Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:
function __destruct()
{
$num_connections--;
}
Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:
echo DB::num_connections;
Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it's best to create just one, and share it (this is called a Singleton Pattern).
Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).
Static Method Example:
public static function prettyName($first_name, $last_name)
{
echo ucfirst($first_name).' '.ucfirst($last_name);
}
echo Person::prettyName($derek->first_name, $derek->last_name);
As you can see, public static function prettyName knows nothing about the object. It's just working with the parameters you pass in, like a normal function that's not part of an object. Why bother, then, if we could just have it not as part of the object?
First, attaching functions to objects helps you keep things organized, so you know where to find them.
Second, it prevents naming conflicts. In a big project, you're likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it's no problem at all. No conflict. Yay static methods!
SELF::
If you are coding outside the object that has the static method you want to refer to, you must call it using the object's name View::format_phone_number($phone_number);
If you are coding inside the object that has the static method you want to refer to, you can either use the object's name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut
The same goes for static variables:
Example: View::templates_path versus self::templates_path
Inside the DB class, if we were referring to a static method of some other object, we would use the object's name:
Example: Session::getUsersOnline();
But if the DB class wanted to refer to its own static variable, it would just say self:
Example: self::connection;
From this blog post:
self refers to the current class
self can be used to call static functions and reference static member variables
self can be used inside static functions
self can also turn off polymorphic behavior by bypassing the vtable
$this refers to the current object
$this can be used to call static functions
$this should not be used to call static member variables. Use self instead.
$this can not be used inside static functions
In PHP, you use the self keyword to access static properties and methods.
The problem is that you can replace $this->method() with self::method()anywhere, regardless if method() is declared static or not. So which one should you use?
Consider this code:
class ParentClass {
function test() {
self::who(); // will output 'parent'
$this->who(); // will output 'child'
}
function who() {
echo 'parent';
}
}
class ChildClass extends ParentClass {
function who() {
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
In this example, self::who() will always output ‘parent’, while $this->who() will depend on what class the object has.
Now we can see that self refers to the class in which it is called, while $this refers to the class of the current object.
So, you should use self only when $this is not available, or when you don’t want to allow descendant classes to overwrite the current method.
Inside a class definition, $this refers to the current object, while self refers to the current class.
It is necessary to refer to a class element using self, and refer to an object element using $this.
self::STAT // refer to a constant value
self::$stat // static variable
$this->stat // refer to an object variable
self refers to the current class (in which it is called),
$this refers to the current object.
You can use static instead of self.
See the example:
class ParentClass {
function test() {
self::which(); // Outputs 'parent'
$this->which(); // Outputs 'child'
}
function which() {
echo 'parent';
}
}
class ChildClass extends ParentClass {
function which() {
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
Output:
parent
child
Here is an example of correct usage of $this and self for non-static
and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
The object pointer $this to refers to the current object.
The class value static refers to the current object.
The class value self refers to the exact class it was defined in.
The class value parent refers to the parent of the exact class it was defined in.
See the following example which shows overloading.
<?php
class A {
public static function newStaticClass()
{
return new static;
}
public static function newSelfClass()
{
return new self;
}
public function newThisClass()
{
return new $this;
}
}
class B extends A
{
public function newParentClass()
{
return new parent;
}
}
$b = new B;
var_dump($b::newStaticClass()); // B
var_dump($b::newSelfClass()); // A because self belongs to "A"
var_dump($b->newThisClass()); // B
var_dump($b->newParentClass()); // A
class C extends B
{
public static function newSelfClass()
{
return new self;
}
}
$c = new C;
var_dump($c::newStaticClass()); // C
var_dump($c::newSelfClass()); // C because self now points to "C" class
var_dump($c->newThisClass()); // C
var_dump($b->newParentClass()); // A because parent was defined *way back* in class "B"
Most of the time you want to refer to the current class which is why you use static or $this. However, there are times when you need self because you want the original class regardless of what extends it. (Very, Very seldom)
According to Static Keyword, there isn't any $self. There is only $this, for referring to the current instance of the class (the object), and self, which can be used to refer to static members of a class. The difference between an object instance and a class comes into play here.
I believe the question was not whether you can call the static member of the class by calling ClassName::staticMember. The question was what's the difference between using self::classmember and $this->classmember.
For example, both of the following examples work without any errors, whether you use self:: or $this->
class Person{
private $name;
private $address;
public function __construct($new_name,$new_address){
$this->name = $new_name;
$this->address = $new_address;
}
}
class Person{
private $name;
private $address;
public function __construct($new_name,$new_address){
self::$name = $new_name;
self::$address = $new_address;
}
}
Here is a small benchmark (7.2.24 on repl.it):
Speed (in seconds) Percentage
$this-> 0.91760206222534 100
self:: 1.0047659873962 109.49909865716
static:: 0.98066782951355 106.87288857386
Results for 4 000 000 runs. Conclusion: it doesn't matter. And here is the code I used:
<?php
class Foo
{
public function calling_this() { $this->called(); }
public function calling_self() { self::called(); }
public function calling_static() { static::called(); }
public static function called() {}
}
$foo = new Foo();
$n = 4000000;
$times = [];
// warmup
for ($i = 0; $i < $n; $i++) { $foo->calling_this(); }
for ($i = 0; $i < $n; $i++) { $foo->calling_self(); }
for ($i = 0; $i < $n; $i++) { $foo->calling_static(); }
$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_this(); }
$times["this"] = microtime(true)-$start;
$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_self(); }
$times["self"] = microtime(true)-$start;
$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_static(); }
$times["static"] = microtime(true)-$start;
$min = min($times);
echo $times["this"] . "\t" . ($times["this"] / $min)*100 . "\n";
echo $times["self"] . "\t" . ($times["self"] / $min)*100 . "\n";
echo $times["static"] . "\t" . ($times["static"] / $min)*100 . "\n";
When self is used with the :: operator it refers to the current class, which can be done both in static and non-static contexts. $this refers to the object itself. In addition, it is perfectly legal to use $this to call static methods (but not to refer to fields).
I ran into the same question and the simple answer was:
$this requires an instance of the class
self:: doesn't
Whenever you are using static methods or static attributes and want to call them without having an object of the class instantiated, you need to use self: to call them, because $this always requires an object to be created.
Additionally since $this:: has not been discussed yet.
For informational purposes only, as of PHP 5.3 when dealing with instantiated objects to get the current scope value, as opposed to using static::, one can alternatively use $this:: like so.
http://ideone.com/7etRHy
class Foo
{
const NAME = 'Foo';
//Always Foo::NAME (Foo) due to self
protected static $staticName = self::NAME;
public function __construct()
{
echo $this::NAME;
}
public function getStaticName()
{
echo $this::$staticName;
}
}
class Bar extends Foo
{
const NAME = 'FooBar';
/**
* override getStaticName to output Bar::NAME
*/
public function getStaticName()
{
$this::$staticName = $this::NAME;
parent::getStaticName();
}
}
$foo = new Foo; //outputs Foo
$bar = new Bar; //outputs FooBar
$foo->getStaticName(); //outputs Foo
$bar->getStaticName(); //outputs FooBar
$foo->getStaticName(); //outputs FooBar
Using the code above is not common or recommended practice, but is simply to illustrate its usage, and is to act as more of a "Did you know?" in reference to the original poster's question.
It also represents the usage of $object::CONSTANT for example echo $foo::NAME; as opposed to $this::NAME;
$this refers to the current class object, and self refers to the current class (Not object). The class is the blueprint of the object. So you define a class, but you construct objects.
So in other words, use self for static and this for none-static members or methods.
Also in a child/parent scenario, self / parent is mostly used to identify child and parent class members and methods.
Use self if you want to call a method of a class without creating an object/instance of that class, thus saving RAM (sometimes use self for that purpose). In other words, it is actually calling a method statically. Use this for object perspective.
self:: A keyword used for the current class and basically it is used to access static members, methods, and constants. But in case of $this, you cannot call the static member, method, and functions.
You can use the self:: keyword in another class and access the static members, method, and constants. When it will be extended from the parent class and the same in case of the $this keyword. You can access the non-static members, method and function in another class when it will be extended from the parent class.
The code given below is an example of the self:: and $this keywords. Just copy and paste the code in your code file and see the output.
class cars{
var $doors = 4;
static $car_wheel = 4;
public function car_features(){
echo $this->doors . " Doors <br>";
echo self::$car_wheel . " Wheels <br>";
}
}
class spec extends cars{
function car_spec(){
print(self::$car_wheel . " Doors <br>");
print($this->doors . " Wheels <br>");
}
}
/********Parent class output*********/
$car = new cars;
print_r($car->car_features());
echo "------------------------<br>";
/********Extend class from another class output**********/
$car_spec_show = new spec;
print($car_spec_show->car_spec());
Case 1: Use self can be used for class constants
class classA {
const FIXED_NUMBER = 4;
self::POUNDS_TO_KILOGRAMS
}
If you want to call it outside of the class, use classA::POUNDS_TO_KILOGRAMS to access the constants
Case 2: For static properties
class classC {
public function __construct() {
self::$_counter++; $this->num = self::$_counter;
}
}
According to php.net there are three special keywords in this context: self, parent and static. They are used to access properties or methods from inside the class definition.
$this, on the other hand, is used to call an instance and methods of any class as long as that class is accessible.

What is the true definition of $this in PHP?

I currently am using PHP and was reading the PHP manual but still have a problem with $this.
Is $this something global or is it is just another variable name to build objects on?
Here is an example:
public function using_a_function($variable1, $variable2, $variable3)
{
$params = array(
'associative1' => $variable1,
'associative2' => $variable2,
'associative3' => $variable3
);
$params['associative4'] = $this->get_function1($params);
return $this->get_function2($params);
}
How would $this work for the return function? I guess I am confused on how this function builds. I understand building the associate array part with a name being a valuekey names => value, but $this throws me off on this example.
$this is only used in object oriented programming (OOP) and refers to the current object.
class SomeObject{
public function returnThis(){
return $this;
}
}
$object = new SomeObject();
var_dump($object === $object->returnThis()); // true
This is used inside the object to reach member variables and methods.
class SomeOtherClass{
private $variable;
public function publicMethod(){
$this->variable;
$this->privateMethod();
}
private function privateMethod(){
//
}
}
It is refered to as the Object scope, lets use an example class.
Class Example
{
private $property;
public function A($foo)
{
$this->property = $foo;
// we are telling the method to look at the object scope not the method scope
}
public function B()
{
return self::property; // self:: is the same as $this
}
}
We can now instance our object and use it in another way also:
$e = new Example;
$e::A('some text');
// would do the same as
$e->A('some other text');
This is just a way of accessing the scope of the Object because methods cannot access other method scopes.
You can also extend a class and use the parent:: to call the class extension scope, for example:
Class Db extends PDO
{
public function __construct()
{
parent::__construct(....
Which would access the PDO construct method rather than its own construct method.
In your case, the method is calling other methods that are in the object. Which can be called using $this-> or self::

PHP new static($variable)

$model = new static($variable);
All these are within a method inside a class, I am trying to technically understand what this piece of code does. I ran around in the Google world. But can't find anything that leads me to an answer. Is this just another way of saying.
$model = new static $variable;
Also what about this
$model = new static;
Does this mean I'm initializing a variable and settings it's value to null but I am just persisting the variable not to lose the value after running the method?
static in this case means the current object scope. It is used in late static binding.
Normally this is going to be the same as using self. The place it differs is when you have a object heirarchy where the reference to the scope is defined on a parent but is being called on the child. self in that case would reference the parents scope whereas static would reference the child's
class A{
function selfFactory(){
return new self();
}
function staticFactory(){
return new static();
}
}
class B extends A{
}
$b = new B();
$a1 = $b->selfFactory(); // a1 is an instance of A
$a2 = $b->staticFactory(); // a2 is an instance of B
It's easiest to think about self as being the defining scope and static being the current object scope.
self is simply a "shortcut name" for the class it occurs in. static is its newer late static binding cousin, which always refers to the current class. I.e. when extending a class, static can also refer to the child class if called from the child context.
new static just means make new instance of the current class and is simply the more dynamic cousin of new self.
And yeah, static == more dynamic is weird.
You have to put it in the context of a class where static is a reference to the class it is called in. We can optionally pass $variable as a parameter to the __construct function of the instance you are creating.
Like so:
class myClass {
private $variable1;
public function __construct($variable2) {
$this->variable1 = $variable2;
}
public static function instantiator() {
$variable3 = 'some parameter';
$model = new static($variable3); // <-this where it happens.
return $model;
}
}
Here static refers to myClass and we pass the variable 'some parameter' as a parameter to the __construct function.
You can use new static() to instantiate a group of class objects from within the class, and have it work with extensions to the class as well.
class myClass {
$some_value = 'foo';
public function __construct($id) {
if($this->validId($id)) {
$this->load($id);
}
}
protected function validId($id) {
// check if id is valid.
return true; // or false, depending
}
protected function load($id) {
// do a db query and populate the object's properties
}
public static function getBy($property, $value) {
// 1st check to see if $property is a valid property
// if yes, then query the db for all objects that match
$matching_objects = array();
foreach($matching as $id) {
$matching_objects[] = new static($id); // calls the constructor from the class it is called from, which is useful for inheritance.
}
return $matching_objects;
}
}
myChildClass extends myClass {
$some_value = 'bar'; //
}
$child_collection = myChildClass::getBy('color','red'); // gets all red ones
$child_object = $child_collection[0];
print_r($child_object); // you'll see it's an object of myChildClass
The keyword new is used to make an object of already defined class
$model = new static($variable);
so here there is an object of model created which is an instance of class static

When would you use the $this keyword in PHP?

When would you use the $this keyword in PHP? From what I understand $this refers to the object created without knowing the objects name.
Also the keyword $this can only be used within a method?
An example would be great to show when you can use $this.
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
Some examples of the $this pseudo-variable:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
}
}
$a = new A();
$a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
The above example will output:
$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.
The most common use case is within Object Oriented Programming, while defining or working within a class. For example:
class Horse {
var $running = false;
function run() {
$this->running = true;
}
}
As you can see, within the run function, we can use the $this variable to refer to the instance of the Horse class that we are "in". So the other thing to keep in mind is that if you create 2 Horse classes, the $this variable inside of each one will refer to that specific instance of the Horse class, not to them both.
You would only use $this if you are doing Object Oriented programming in PHP. Meaning if you are creating classes. Here is an example:
class Item {
protected $name, $price, $qty, $total;
public function __construct($iName, $iPrice, $iQty) {
$this->name = $iName;
$this->price = $iPrice;
$this->qty = $iQty;
$this->calculate();
}
}
$this is used to make a reference to the current instance of an object.
So you can do things like:
class MyClass {
private $name;
public function setName($name) {
$this->name = $name;
}
//vs
public function setName($pName) {
$name = $pName;
}
}
Also another cool use is that you can chain methods:
class MyClass2 {
private $firstName;
private $lastName;
public function setFirstName($name) {
$this->firstName = $name;
return $this;
}
public function setLastName($name) {
$this->lastName = $name;
return $this;
}
public function sayHello() {
print "Hello {$this->firstName} {$this->lastName}";
}
}
//And now you can do:
$newInstance = new MyClass2;
$newInstance->setFirstName("John")->setLastName("Doe")->sayHello();
It's used in Object-oriented Programming (OOP):
<?php
class Example
{
public function foo()
{
//code
}
public function bar()
{
$this->foo();
}
}
The pseudo-variable $this is available
when a method is called from within an
object context. $this is a reference
to the calling object (usually the
object to which the method belongs,
but possibly another object, if the
method is called statically from the
context of a secondary object).
Used for when you want to work with local variables.
You can also read more about it from here.
function bark() {
print "{$this->Name} says Woof!\n";
}
One time I know I end up using the this equivalent in other languages is to implement a 'Fluent' interface; each class method which would otherwise return void instead returns this, so that method calls can be easily chained together.
public function DoThis(){
//Do stuff here...
return $this;
}
public function DoThat(){
//do other stuff here...
return $this;
}
The above could be called like so:
myObject->DoThis()->DoThat();
Which can be useful for some things.
$this is used when you have created a new instance of an object.
For example, imagine this :
class Test {
private $_hello = "hello";
public function getHello () {
echo $this->_hello; // note that I removed the $ from _hello !
}
public function setHello ($hello) {
$this->_hello = $hello;
}
}
In order to access to the method getHello, I have to create a new instance of the class Test, like this :
$obj = new Test ();
// Then, I can access to the getHello method :
echo $obj->getHello ();
// will output "hello"
$obj->setHello("lala");
echo $obj->getHello ();
// will output "lala"
In fact, $this is used inside the class, when instancied. It is refered as a scope.
Inside your class you use $this (for accessing *$_hello* for example) but outside the class, $this does NOT refer to the elements inside your class (like *$_hello*), it's $obj that does.
Now, the main difference between $obj and $this is since $obj access your class from the outside, some restrictions happens : if you define something private or protected in your class, like my variable *$_hello*, $obj CAN'T access it (it's private!) but $this can, becase $this leave inside the class.
no i think ur idea is wrong.. $this is used when refers to a object of the same class.. like this
think we have a variable value $var and in THAT instance of that object should be set to 5
$this->var=5;
The use $this is to reference methods or instance variables belonging to the current object
$this->name = $name
or
$this->callSomeMethod()
that is going to use the variable or method implemented in the current object subclassed or not.
If you would like to specifically call an implementation of of the parent class you would do something like
parent::callSomeMethod()
Whenever you want to use a variable that is outside of the function but inside the same class, you use $this. $this refers to the current php class that the property or function you are going to access resides in. It is a core php concept.
<?php
class identity {
public $name;
public $age;
public function display() {
return $this->name . 'is'. $this->age . 'years old';
}
}
?>

When should I use 'self' over '$this'?

In PHP 5, what is the difference between using self and $this?
When is each appropriate?
Short Answer
Use $this to refer to the current
object. Use self to refer to the
current class. In other words, use
$this->member for non-static members,
use self::$member for static members.
Full Answer
Here is an example of correct usage of $this and self for non-static and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
Here is an example of incorrect usage of $this and self for non-static and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo self::$non_static_member . ' '
. $this->static_member;
}
}
new X();
?>
Here is an example of polymorphism with $this for member functions:
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
$this->foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
Here is an example of suppressing polymorphic behaviour by using self for member functions:
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
self::foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.
From http://www.phpbuilder.com/board/showthread.php?t=10354489:
By http://board.phpbuilder.com/member.php?145249-laserlight
The keyword self does NOT refer merely to the 'current class', at least not in a way that restricts you to static members. Within the context of a non-static member, self also provides a way of bypassing the vtable (see wiki on vtable) for the current object. Just as you can use parent::methodName() to call the parents version of a function, so you can call self::methodName() to call the current classes implementation of a method.
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function getTitle() {
return $this->getName()." the person";
}
public function sayHello() {
echo "Hello, I'm ".$this->getTitle()."<br/>";
}
public function sayGoodbye() {
echo "Goodbye from ".self::getTitle()."<br/>";
}
}
class Geek extends Person {
public function __construct($name) {
parent::__construct($name);
}
public function getTitle() {
return $this->getName()." the geek";
}
}
$geekObj = new Geek("Ludwig");
$geekObj->sayHello();
$geekObj->sayGoodbye();
This will output:
Hello, I'm Ludwig the geek
Goodbye from Ludwig the person
sayHello() uses the $this pointer, so the vtable is invoked to call Geek::getTitle().
sayGoodbye() uses self::getTitle(), so the vtable is not used, and Person::getTitle() is called. In both cases, we are dealing with the method of an instantiated object, and have access to the $this pointer within the called functions.
Do not use self::. Use static::*
There is another aspect of self:: that is worth mentioning. Annoyingly, self:: refers to the scope at the point of definition, not at the point of execution. Consider this simple class with two methods:
class Person
{
public static function status()
{
self::getStatus();
}
protected static function getStatus()
{
echo "Person is alive";
}
}
If we call Person::status() we will see "Person is alive" . Now consider what happens when we make a class that inherits from this:
class Deceased extends Person
{
protected static function getStatus()
{
echo "Person is deceased";
}
}
Calling Deceased::status() we would expect to see "Person is deceased". However, we see "Person is alive" as the scope contains the original method definition when the call to self::getStatus() was defined.
PHP 5.3 has a solution. The static:: resolution operator implements "late static binding" which is a fancy way of saying that it's bound to the scope of the class called. Change the line in status() to static::getStatus() and the results are what you would expect. In older versions of PHP you will have to find a kludge to do this.
See PHP Documentation
So to answer the question not as asked...
$this-> refers to the current object (an instance of a class), whereas static:: refers to a class.
To really understand what we're talking about when we talk about self versus $this, we need to actually dig into what's going on at a conceptual and a practical level. I don't really feel any of the answers do this appropriately, so here's my attempt.
Let's start off by talking about what a class and an object is.
Classes And Objects, Conceptually
So, what is a class? A lot of people define it as a blueprint or a template for an object. In fact, you can read more About Classes In PHP Here. And to some extent that's what it really is. Let's look at a class:
class Person {
public $name = 'my name';
public function sayHello() {
echo "Hello";
}
}
As you can tell, there is a property on that class called $name and a method (function) called sayHello().
It's very important to note that the class is a static structure. Which means that the class Person, once defined, is always the same everywhere you look at it.
An object on the other hand is what's called an instance of a Class. What that means is that we take the "blueprint" of the class, and use it to make a dynamic copy. This copy is now specifically tied to the variable it's stored in. Therefore, any changes to an instance is local to that instance.
$bob = new Person;
$adam = new Person;
$bob->name = 'Bob';
echo $adam->name; // "my name"
We create new instances of a class using the new operator.
Therefore, we say that a Class is a global structure, and an Object is a local structure. Don't worry about that funny -> syntax, we're going to go into that in a little bit.
One other thing we should talk about, is that we can check if an instance is an instanceof a particular class: $bob instanceof Person which returns a boolean if the $bob instance was made using the Person class, or a child of Person.
Defining State
So let's dig a bit into what a class actually contains. There are 5 types of "things" that a class contains:
Properties - Think of these as variables that each instance will contain.
class Foo {
public $bar = 1;
}
Static Properties - Think of these as variables that are shared at the class level. Meaning that they are never copied by each instance.
class Foo {
public static $bar = 1;
}
Methods - These are functions which each instance will contain (and operate on instances).
class Foo {
public function bar() {}
}
Static Methods - These are functions which are shared across the entire class. They do not operate on instances, but instead on the static properties only.
class Foo {
public static function bar() {}
}
Constants - Class resolved constants. Not going any deeper here, but adding for completeness:
class Foo {
const BAR = 1;
}
So basically, we're storing information on the class and object container using "hints" about static which identify whether the information is shared (and hence static) or not (and hence dynamic).
State and Methods
Inside of a method, an object's instance is represented by the $this variable. The current state of that object is there, and mutating (changing) any property will result in a change to that instance (but not others).
If a method is called statically, the $this variable is not defined. This is because there's no instance associated with a static call.
The interesting thing here is how static calls are made. So let's talk about how we access the state:
Accessing State
So now that we have stored that state, we need to access it. This can get a bit tricky (or way more than a bit), so let's split this into two viewpoints: from outside of an instance/class (say from a normal function call, or from the global scope), and inside of an instance/class (from within a method on the object).
From Outside Of An Instance/Class
From the outside of an instance/class, our rules are quite simple and predictable. We have two operators, and each tells us immediately if we're dealing with an instance or a class static:
-> - object-operator - This is always used when we're accessing an instance.
$bob = new Person;
echo $bob->name;
It's important to note that calling Person->foo does not make sense (since Person is a class, not an instance). Therefore, that is a parse error.
:: - scope-resolution-operator - This is always used to access a Class static property or method.
echo Foo::bar()
Additionally, we can call a static method on an object in the same way:
echo $foo::bar()
It's extremely important to note that when we do this from outside, the object's instance is hidden from the bar() method. Meaning that it's the exact same as running:
$class = get_class($foo);
$class::bar();
Therefore, $this is not defined in the static call.
From Inside Of An Instance/Class
Things change a bit here. The same operators are used, but their meaning becomes significantly blurred.
The object-operator -> is still used to make calls to the object's instance state.
class Foo {
public $a = 1;
public function bar() {
return $this->a;
}
}
Calling the bar() method on $foo (an instance of Foo) using the object-operator: $foo->bar() will result in the instance's version of $a.
So that's how we expect.
The meaning of the :: operator though changes. It depends on the context of the call to the current function:
Within a static context
Within a static context, any calls made using :: will also be static. Let's look at an example:
class Foo {
public function bar() {
return Foo::baz();
}
public function baz() {
return isset($this);
}
}
Calling Foo::bar() will call the baz() method statically, and hence $this will not be populated. It's worth noting that in recent versions of PHP (5.3+) this will trigger an E_STRICT error, because we're calling non-static methods statically.
Within an instance context
Within an instance context on the other hand, calls made using :: depend on the receiver of the call (the method we're calling). If the method is defined as static, then it will use a static call. If it's not, it will forward the instance information.
So, looking at the above code, calling $foo->bar() will return true, since the "static" call happens inside of an instance context.
Make sense? Didn't think so. It's confusing.
Short-Cut Keywords
Because tying everything together using class names is rather dirty, PHP provides 3 basic "shortcut" keywords to make scope resolving easier.
self - This refers to the current class name. So self::baz() is the same as Foo::baz() within the Foo class (any method on it).
parent - This refers to the parent of the current class.
static - This refers to the called class. Thanks to inheritance, child classes can override methods and static properties. So calling them using static instead of a class name allows us to resolve where the call came from, rather than the current level.
Examples
The easiest way to understand this is to start looking at some examples. Let's pick a class:
class Person {
public static $number = 0;
public $id = 0;
public function __construct() {
self::$number++;
$this->id = self::$number;
}
public $name = "";
public function getName() {
return $this->name;
}
public function getId() {
return $this->id;
}
}
class Child extends Person {
public $age = 0;
public function __construct($age) {
$this->age = $age;
parent::__construct();
}
public function getName() {
return 'child: ' . parent::getName();
}
}
Now, we're also looking at inheritance here. Ignore for a moment that this is a bad object model, but let's look at what happens when we play with this:
$bob = new Person;
$bob->name = "Bob";
$adam = new Person;
$adam->name = "Adam";
$billy = new Child;
$billy->name = "Billy";
var_dump($bob->getId()); // 1
var_dump($adam->getId()); // 2
var_dump($billy->getId()); // 3
So the ID counter is shared across both instances and the children (because we're using self to access it. If we used static, we could override it in a child class).
var_dump($bob->getName()); // Bob
var_dump($adam->getName()); // Adam
var_dump($billy->getName()); // child: Billy
Note that we're executing the Person::getName() instance method every time. But we're using the parent::getName() to do it in one of the cases (the child case). This is what makes this approach powerful.
Word Of Caution #1
Note that the calling context is what determines if an instance is used. Therefore:
class Foo {
public function isFoo() {
return $this instanceof Foo;
}
}
Is not always true.
class Bar {
public function doSomething() {
return Foo::isFoo();
}
}
$b = new Bar;
var_dump($b->doSomething()); // bool(false)
Now it is really weird here. We're calling a different class, but the $this that gets passed to the Foo::isFoo() method is the instance of $bar.
This can cause all sorts of bugs and conceptual WTF-ery. So I'd highly suggest avoiding the :: operator from within instance methods on anything except those three virtual "short-cut" keywords (static, self, and parent).
Word Of Caution #2
Note that static methods and properties are shared by everyone. That makes them basically global variables. With all the same problems that come with globals. So I would be really hesitant to store information in static methods/properties unless you're comfortable with it being truly global.
Word Of Caution #3
In general you'll want to use what's known as Late-Static-Binding by using static instead of self. But note that they are not the same thing, so saying "always use static instead of self is really short-sighted. Instead, stop and think about the call you want to make and think if you want child classes to be able to override that static resolved call.
TL/DR
Too bad, go back and read it. It may be too long, but it's that long because this is a complex topic
TL/DR #2
Ok, fine. In short, self is used to reference the current class name within a class, where as $this refers to the current object instance. Note that self is a copy/paste short-cut. You can safely replace it with your class name, and it'll work fine. But $this is a dynamic variable that can't be determined ahead of time (and may not even be your class).
TL/DR #3
If the object-operator is used (->), then you always know you're dealing with an instance. If the scope-resolution-operator is used (::), you need more information about the context (are we in an object-context already? Are we outside of an object? etc).
self (not $self) refers to the type of class, whereas $this refers to the current instance of the class. self is for use in static member functions to allow you to access static member variables. $this is used in non-static member functions, and is a reference to the instance of the class on which the member function was called.
Because this is an object, you use it like: $this->member
Because self is not an object, it's basically a type that automatically refers to the current class. You use it like: self::member
$this-> is used to refer to a specific instance of a class's variables (member variables) or methods.
Example:
$derek = new Person();
$derek is now a specific instance of Person.
Every Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name
ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word "static" with "shared". Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).
Static Variables Example:
Pretend we have a database class with a single member variable: static $num_connections;
Now, put this in the constructor:
function __construct()
{
if(!isset $num_connections || $num_connections==null)
{
$num_connections=0;
}
else
{
$num_connections++;
}
}
Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:
function __destruct()
{
$num_connections--;
}
Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:
echo DB::num_connections;
Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it's best to create just one, and share it (this is called a Singleton Pattern).
Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).
Static Method Example:
public static function prettyName($first_name, $last_name)
{
echo ucfirst($first_name).' '.ucfirst($last_name);
}
echo Person::prettyName($derek->first_name, $derek->last_name);
As you can see, public static function prettyName knows nothing about the object. It's just working with the parameters you pass in, like a normal function that's not part of an object. Why bother, then, if we could just have it not as part of the object?
First, attaching functions to objects helps you keep things organized, so you know where to find them.
Second, it prevents naming conflicts. In a big project, you're likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it's no problem at all. No conflict. Yay static methods!
SELF::
If you are coding outside the object that has the static method you want to refer to, you must call it using the object's name View::format_phone_number($phone_number);
If you are coding inside the object that has the static method you want to refer to, you can either use the object's name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut
The same goes for static variables:
Example: View::templates_path versus self::templates_path
Inside the DB class, if we were referring to a static method of some other object, we would use the object's name:
Example: Session::getUsersOnline();
But if the DB class wanted to refer to its own static variable, it would just say self:
Example: self::connection;
From this blog post:
self refers to the current class
self can be used to call static functions and reference static member variables
self can be used inside static functions
self can also turn off polymorphic behavior by bypassing the vtable
$this refers to the current object
$this can be used to call static functions
$this should not be used to call static member variables. Use self instead.
$this can not be used inside static functions
In PHP, you use the self keyword to access static properties and methods.
The problem is that you can replace $this->method() with self::method()anywhere, regardless if method() is declared static or not. So which one should you use?
Consider this code:
class ParentClass {
function test() {
self::who(); // will output 'parent'
$this->who(); // will output 'child'
}
function who() {
echo 'parent';
}
}
class ChildClass extends ParentClass {
function who() {
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
In this example, self::who() will always output ‘parent’, while $this->who() will depend on what class the object has.
Now we can see that self refers to the class in which it is called, while $this refers to the class of the current object.
So, you should use self only when $this is not available, or when you don’t want to allow descendant classes to overwrite the current method.
Inside a class definition, $this refers to the current object, while self refers to the current class.
It is necessary to refer to a class element using self, and refer to an object element using $this.
self::STAT // refer to a constant value
self::$stat // static variable
$this->stat // refer to an object variable
self refers to the current class (in which it is called),
$this refers to the current object.
You can use static instead of self.
See the example:
class ParentClass {
function test() {
self::which(); // Outputs 'parent'
$this->which(); // Outputs 'child'
}
function which() {
echo 'parent';
}
}
class ChildClass extends ParentClass {
function which() {
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
Output:
parent
child
Here is an example of correct usage of $this and self for non-static
and static member variables:
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
The object pointer $this to refers to the current object.
The class value static refers to the current object.
The class value self refers to the exact class it was defined in.
The class value parent refers to the parent of the exact class it was defined in.
See the following example which shows overloading.
<?php
class A {
public static function newStaticClass()
{
return new static;
}
public static function newSelfClass()
{
return new self;
}
public function newThisClass()
{
return new $this;
}
}
class B extends A
{
public function newParentClass()
{
return new parent;
}
}
$b = new B;
var_dump($b::newStaticClass()); // B
var_dump($b::newSelfClass()); // A because self belongs to "A"
var_dump($b->newThisClass()); // B
var_dump($b->newParentClass()); // A
class C extends B
{
public static function newSelfClass()
{
return new self;
}
}
$c = new C;
var_dump($c::newStaticClass()); // C
var_dump($c::newSelfClass()); // C because self now points to "C" class
var_dump($c->newThisClass()); // C
var_dump($b->newParentClass()); // A because parent was defined *way back* in class "B"
Most of the time you want to refer to the current class which is why you use static or $this. However, there are times when you need self because you want the original class regardless of what extends it. (Very, Very seldom)
According to Static Keyword, there isn't any $self. There is only $this, for referring to the current instance of the class (the object), and self, which can be used to refer to static members of a class. The difference between an object instance and a class comes into play here.
I believe the question was not whether you can call the static member of the class by calling ClassName::staticMember. The question was what's the difference between using self::classmember and $this->classmember.
For example, both of the following examples work without any errors, whether you use self:: or $this->
class Person{
private $name;
private $address;
public function __construct($new_name,$new_address){
$this->name = $new_name;
$this->address = $new_address;
}
}
class Person{
private $name;
private $address;
public function __construct($new_name,$new_address){
self::$name = $new_name;
self::$address = $new_address;
}
}
Here is a small benchmark (7.2.24 on repl.it):
Speed (in seconds) Percentage
$this-> 0.91760206222534 100
self:: 1.0047659873962 109.49909865716
static:: 0.98066782951355 106.87288857386
Results for 4 000 000 runs. Conclusion: it doesn't matter. And here is the code I used:
<?php
class Foo
{
public function calling_this() { $this->called(); }
public function calling_self() { self::called(); }
public function calling_static() { static::called(); }
public static function called() {}
}
$foo = new Foo();
$n = 4000000;
$times = [];
// warmup
for ($i = 0; $i < $n; $i++) { $foo->calling_this(); }
for ($i = 0; $i < $n; $i++) { $foo->calling_self(); }
for ($i = 0; $i < $n; $i++) { $foo->calling_static(); }
$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_this(); }
$times["this"] = microtime(true)-$start;
$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_self(); }
$times["self"] = microtime(true)-$start;
$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_static(); }
$times["static"] = microtime(true)-$start;
$min = min($times);
echo $times["this"] . "\t" . ($times["this"] / $min)*100 . "\n";
echo $times["self"] . "\t" . ($times["self"] / $min)*100 . "\n";
echo $times["static"] . "\t" . ($times["static"] / $min)*100 . "\n";
When self is used with the :: operator it refers to the current class, which can be done both in static and non-static contexts. $this refers to the object itself. In addition, it is perfectly legal to use $this to call static methods (but not to refer to fields).
I ran into the same question and the simple answer was:
$this requires an instance of the class
self:: doesn't
Whenever you are using static methods or static attributes and want to call them without having an object of the class instantiated, you need to use self: to call them, because $this always requires an object to be created.
Additionally since $this:: has not been discussed yet.
For informational purposes only, as of PHP 5.3 when dealing with instantiated objects to get the current scope value, as opposed to using static::, one can alternatively use $this:: like so.
http://ideone.com/7etRHy
class Foo
{
const NAME = 'Foo';
//Always Foo::NAME (Foo) due to self
protected static $staticName = self::NAME;
public function __construct()
{
echo $this::NAME;
}
public function getStaticName()
{
echo $this::$staticName;
}
}
class Bar extends Foo
{
const NAME = 'FooBar';
/**
* override getStaticName to output Bar::NAME
*/
public function getStaticName()
{
$this::$staticName = $this::NAME;
parent::getStaticName();
}
}
$foo = new Foo; //outputs Foo
$bar = new Bar; //outputs FooBar
$foo->getStaticName(); //outputs Foo
$bar->getStaticName(); //outputs FooBar
$foo->getStaticName(); //outputs FooBar
Using the code above is not common or recommended practice, but is simply to illustrate its usage, and is to act as more of a "Did you know?" in reference to the original poster's question.
It also represents the usage of $object::CONSTANT for example echo $foo::NAME; as opposed to $this::NAME;
$this refers to the current class object, and self refers to the current class (Not object). The class is the blueprint of the object. So you define a class, but you construct objects.
So in other words, use self for static and this for none-static members or methods.
Also in a child/parent scenario, self / parent is mostly used to identify child and parent class members and methods.
Use self if you want to call a method of a class without creating an object/instance of that class, thus saving RAM (sometimes use self for that purpose). In other words, it is actually calling a method statically. Use this for object perspective.
self:: A keyword used for the current class and basically it is used to access static members, methods, and constants. But in case of $this, you cannot call the static member, method, and functions.
You can use the self:: keyword in another class and access the static members, method, and constants. When it will be extended from the parent class and the same in case of the $this keyword. You can access the non-static members, method and function in another class when it will be extended from the parent class.
The code given below is an example of the self:: and $this keywords. Just copy and paste the code in your code file and see the output.
class cars{
var $doors = 4;
static $car_wheel = 4;
public function car_features(){
echo $this->doors . " Doors <br>";
echo self::$car_wheel . " Wheels <br>";
}
}
class spec extends cars{
function car_spec(){
print(self::$car_wheel . " Doors <br>");
print($this->doors . " Wheels <br>");
}
}
/********Parent class output*********/
$car = new cars;
print_r($car->car_features());
echo "------------------------<br>";
/********Extend class from another class output**********/
$car_spec_show = new spec;
print($car_spec_show->car_spec());
Case 1: Use self can be used for class constants
class classA {
const FIXED_NUMBER = 4;
self::POUNDS_TO_KILOGRAMS
}
If you want to call it outside of the class, use classA::POUNDS_TO_KILOGRAMS to access the constants
Case 2: For static properties
class classC {
public function __construct() {
self::$_counter++; $this->num = self::$_counter;
}
}
According to php.net there are three special keywords in this context: self, parent and static. They are used to access properties or methods from inside the class definition.
$this, on the other hand, is used to call an instance and methods of any class as long as that class is accessible.

Categories