Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP Self VS This – A Beginner’s Guide

INTRODUCTION
LOOKS THE SAME, BUT DIFFERENT

Welcome to a beginner’s Tutorial on the difference between self and this in PHP. Yes, it is very confusing. Just why does PHP have 2 similar keywords that seemingly refer to the same thing? Long story short, they are 2 totally different creatures – Self refers to the class, and this refers to the object. Need more examples and explanations to crack the mystery? Read on to find out!

I have included a zip file with all the example source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
The Explanation

Section B
Summary & More

Extra
Source Code Download

Closing
Not The Same

SECTION A
THE EXPLANATION

To fully understand the differences between this and self, you will also need to understand some of the basics of object-oriented programming (OOP). Let us walk through the mysteries step-by-step in this section.

WE USE “THIS” ON OBJECTS

1-this.php
legs = $l;
    $this->wings = $w;
  }

  function introduce () {
    // $this refers to the OBJECT'S properties
    echo "This animal has $this->legs legs and $this->wings wings.
"; } } $doge = new Animal(4, 0); $chicken = new Animal(2, 2); $doge->introduce(); $chicken->introduce(); ?>
The output
This animal has 4 legs and 0 wings.
This animal has 2 legs and 2 wings.

Let us start with the easier $this first. Remember that classes are kind of like templates in OOP? Where we define the common properties and functions? Objects that are created from the class template will also adopt these properties and functions, but they can hold different values – This is where we use $this to refer to the object’s functions and properties.

WE USE “SELF” ON CLASSES

THIS WILL NOT WORK ON CLASSES

So when do we use the self keyword? As you have read earlier in the introduction, when we want to refer to the claass instead. So let us start with a negative example of what happens when we use $this on the class itself:

2a-bad-self.php
legs = $l;
    $this->wings = $w;
  }

  function introduce () {
    echo "This animal has $this->legs legs and $this->wings wings.
"; } } // Directly calling the introduce function of class Animal // ERROR - $this refers to properties of the object, NOT the class itself Animal::introduce(); ?>
The output
Fatal error: Uncaught Error: Using $this when not in object context in D:\http\test\2a-bad-self.php:12 
Stack trace: #0 D:\http\test\2a-bad-self.php(17): Animal::introduce() #1 {main} thrown in D:\http\test\2a-bad-self.php on line 12

SELF WILL NOT WORK ON NON-STATIC

As expected, PHP will complain “using $this when not in object context” – We should be using self instead:

2b-bad-self.php
legs = $l; 
    $this->wings = $w;
  }
 
  function introduce () {
    echo "This animal has " . self::$legs . " legs and " . self::$wings . " wings.
"; } } // ERROR - property is not static Animal::introduce(); ?>
The output
Fatal error: Uncaught Error: Access to undeclared static property: Animal::$legs in D:\http\test\2b-bad-self.php:12
Stack trace: #0 D:\http\test\2b-bad-self.php(17): Animal::introduce() #1 {main} thrown in D:\http\test\2b-bad-self.php on line 12

AND oopsies again, self can only access static members.

THE PROPER SELF

So finally, here is a proper example of self:

2c-good-self.php
legs = $l; 
    $this->wings = $w;
  }

  function introduce () {
    echo "This animal has " . self::$legs . " legs and " . self::$wings . " wings.
"; } } // OK - 0 legs and 0 wings Animal::introduce(); // NOTE - static class properties cannot be changed directly by objects // Take extra care in what you "static" $doge = new Animal(999, 888); // 0 legs and 0 wings $doge->introduce(); ?>

SECTION B
SUMMARY – DIFFERENCES & MORE

The above examples should have pretty much highlighted the main difference between this and self, plus when we should use them. Let us sum up all the difference in this section.

THIS VS SELF

 ThisSelf
Precedencethis is preceded with $ symbol.self is not preceded by any symbols.
OperatorWe use the -> object operator with $this.We use the :: scope resolution operator with self.
Used OnNon-static members of an object.Static members of a class.
Requires Instantiated ObjectYes.No.
Refers ToWe use $this to refer to members of an instantiated object.We use self to refer to members of the class itself.

EXTRA – PARENT

As a small added extra, here is something that is good for you to know as well – Apart from self, we can use the parent keyword to refer to the ancestor:

3-extra-parent.php
legs = $l;
    $this->wings = $w;
  }

  function introduce () {
    echo "This animal has " . self::$heart . " heart, " .$this->legs. " legs, and " . $this->wings . " wings.
"; } } class Doge extends Animal { // This will override the parent introduce function function introduce () { echo "BORK!
"; // But we can still call it with the parent keyword parent::introduce(); } } $pupper = new Doge(3, 5); $pupper->introduce(); ?>

REFERENCES

  • Classes and objects in PHP
  • Scope Resolution Operator in PHP
  • Static keyword in PHP

THE INFOGRAPHIC

PHP Self VS This (click to enlarge)

EXTRA
DOWNLOAD

Finally, here is the download link to all the example source code as promised.

SOURCE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
NOT THE SAME

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand – THIS and SELF may seem to have the same meaning, but they are really referring to 2 different things altogether. If you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post PHP Self VS This – A Beginner’s Guide appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

PHP Self VS This – A Beginner’s Guide

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×