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!

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

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.

WebStorm Mac version
Useful JavaScript development tools
