亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development PHP Tutorial PHP OOP Part-Static property, method and this vs self

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

Jan 04, 2025 pm 04:36 PM

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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

See all articles