search
HomeBackend DevelopmentPHP TutorialPHP OOP Part-Static property, method and this vs self

PHP OOP Part-Static property, method and this vs self

In this series, I will cover the fundamentals of PHP Object-Oriented Programming (OOP). The content will be organized into sequential parts, each focusing on a specific topic. If you're a beginner or unfamiliar with OOP concepts, this series is designed to guide you step by step. In this part, I will discuss about the static property, method and this vs self in PHP. Let's begin the journey of learning PHP OOP together!

What is property and method?

First, let us try to understand properties and methods. When we create multiple objects using a class, each object is allocated a separate memory location. As a result, all the properties and methods of that object are also allocated to that specific memory location.

This means that when we change any property of an object, the change is restricted to that particular object only. It does not affect any other objects because the properties and methods of a class are associated with the respective objects of that class.

To access these properties or methods from outside the class, we need to create an object of that class. However, if we want to access these properties or methods within the class, we can use the $this keyword. The $this keyword represents the current object of the class. We will learn more about the $this keyword later. Let us look at the following example:

Code Example

class Car
{
   public $name;
   public $color;

   function __construct(string $name, string $color)
   {
      $this->name  = $name;
      $this->color = $color;
   }

   public function getValue()
   {
      echo "Car name: $this->name\n";
      echo "Car color: $this->color\n";
   }
}

$tesla = new Car('Zip', 'Blue');
$tesla->getValue();

In this example, we can see that to access the properties of the class, we have used the $this keyword within the methods of the same class. Similarly, to use any method of this class from outside, we have created an object of the class. This is how we typically use the normal properties or methods of a class.

What is static property and method?

However, static properties or methods work differently. When we define a class, it is allocated a memory location only once. Similarly, when we define static properties or methods in a class, they are also allocated to a specific memory location alongside the class itself, but only once.

As a result, if we modify any static property or method later, the change will reflect across all instances of the class. In other words, wherever the static property or method is used, its updated value will be available.

If we want to access static properties or methods from outside the class, we can use the :: (scope resolution operator) without creating an object. Alternatively, we can also access them after creating an object. To access them from within the class, we can use the self keyword or the class name itself. Here, the self keyword represents the class.

We will explore the self keyword in more detail later. Let us look at the following example:

Code Example

class Car
{
   public $name;
   public $color;

   function __construct(string $name, string $color)
   {
      $this->name  = $name;
      $this->color = $color;
   }

   public function getValue()
   {
      echo "Car name: $this->name\n";
      echo "Car color: $this->color\n";
   }
}

$tesla = new Car('Zip', 'Blue');
$tesla->getValue();

In this example, we can see that to access the static properties of the class, we have used the self keyword within the methods of the same class. Additionally, to use a static method from outside the class, we created an object of the class. However, we could also access it directly using the class name along with the :: (scope resolution operator), without creating an object. This is how we typically use the static properties or methods of a class.

In the above example, we can see that using the Car class, we created two objects, $toyota and $bmw, with different data. Now we want to access the values of these objects. If we run the code above, we will see the following output:

Code Example

class Car
{
   public static $name;
   public static $color;

   function __construct($name, $color)
   {
      self::$name = $name;
      self::$color = $color;
   }

   public static function getValue()
   {
      echo "Car name: " . self::$name . "\n";
      echo "Car color: " . self::$color . "\n";
   }
}

$toyota = new Car('Toyota', 'Black');
$bmw = new Car('BMW', 'Orange');

$toyota::getValue();
$bmw::getValue();

Car::getValue();

We can see that both objects are showing the same values. In other words, the values we are getting are from the most recently created object. Even when we try to access the values directly through the class, we still get the same values, i.e., the values of the second object.

The reason for this is quite clear. As mentioned earlier, static properties or methods are created in a single memory location. If the static properties or methods are changed from anywhere, the change affects all instances of the class.

In the example above, when we created the second object, the values of the properties changed as soon as the object was created. This change also affected the previously created object because all objects of the class share the same static properties or methods.

It is important to remember that static properties or methods of a class cannot be used in the same way as normal class properties or methods. You cannot use the → operator to access them. Instead, you must use the ::(scope resolution operator), whether you are accessing them from inside or outside the class.

$this vs self Keyword

What is $this?

We have already seen the usage of the $this and self keywords. Now, let us delve deeper into these concepts to better understand them.

$this is a built-in PHP keyword. When we create one or more objects using a class, the normal properties and methods defined within the class can be accessed using the $this keyword from within the class.

Now, we know that when a class is defined, it is allocated to a specific memory location only once. This might raise a question: if we create multiple objects from this class, will the $this keyword access the properties or methods only once for all objects?

The answer is "No". This is because, as we have already discussed, the $this keyword does not represent the class itself but rather the object created by that class. In other words, $this is directly related to the object. As a result, for every object created, the $this keyword will access the properties and methods of the class separately for each object. Let us look at the following example:

class Car
{
   public $name;
   public $color;

   function __construct(string $name, string $color)
   {
      $this->name  = $name;
      $this->color = $color;
   }

   public function getValue()
   {
      echo "Car name: $this->name\n";
      echo "Car color: $this->color\n";
   }
}

$tesla = new Car('Zip', 'Blue');
$tesla->getValue();

In the previous example, we have used it multiple times, but the usage of $this was not discussed in detail. Now that we have gained some understanding of $this, we can better comprehend its usage. Using this class, we have created objects. Now, we understand that the $this keyword accesses the properties separately for each object.

However, it is important to note that the $this keyword cannot be used inside a static method. Why it cannot be used will be explained shortly.

What is the self keyword?

We already know that when a class is defined, it is allocated to a memory location only once. Similarly, all the static properties and methods within that class are also allocated to the memory location along with the class, only once.

As a result, when we create objects using this class, the static properties or methods are not separately created for each object. This is why we cannot access these static properties or methods using the $this keyword. The $this keyword represents the object of the class, and since static properties or methods are not related to any object but directly to the class itself, they cannot be accessed using $this.

To access static properties or methods within the class, we use the self keyword or the class name along with the ::(scope resolution operator). This is because the self keyword represents the class itself. Let us look at the following example:

class Car
{
   public static $name;
   public static $color;

   function __construct($name, $color)
   {
      self::$name = $name;
      self::$color = $color;
   }

   public static function getValue()
   {
      echo "Car name: " . self::$name . "\n";
      echo "Car color: " . self::$color . "\n";
   }
}

$toyota = new Car('Toyota', 'Black');
$bmw = new Car('BMW', 'Orange');

$toyota::getValue();
$bmw::getValue();

Car::getValue();

In this example, we see that we can easily access static members within a non-static method using the class name or the self keyword with the ::scope resolution operator, because they are related to the class. Therefore, to access them, we do not need to create a separate object.

However, if we want to access non-static members within a static method, we would need to use the $this keyword. But we know that the $this keyword cannot be used within a static method because $this is related to the object, while non-static members are not related to the object. This is the reason we cannot use the $this keyword within a static method.

However, if we need to access non-static members within a static method, we can create an instance or object of the class within the static method and then use the $this keyword to access them, as shown in the example above.

I hope this gives you a clearer understanding of the usage of $this and self keywords. That’s all for today; we’ll continue in the next lesson.

You can connect with me on GitHub and Linkedin.

The above is the detailed content of PHP OOP Part-Static property, method and this vs self. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools