search
HomeBackend DevelopmentPHP TutorialPHP object-oriented basics

  1. class Person
  2. {
  3. //The following are the member attributes of the person
  4. var $name; //The name of the person
  5. var $***; //The gender of the person
  6. var $age ; //The age of the person
  7. //The following is the member method of the person
  8. function say() //The method by which this person can speak
  9. {
  10. echo "This person is talking";
  11. }
  12. function run() //This person Methods that can walk
  13. {
  14. echo "This person is walking";
  15. }
  16. }
  17. ?>
Copy code

3.5. How to instantiate objects

As mentioned above, the unit of PHP object-oriented program is the object, but the object is instantiated through the class. Since our class will be declared, the next step is to instantiate the object. After defining the class, we use the new keyword to generate an object. $Object name = new Class name(); Object->Properties $p1->name; $p2->age; $p3->***; Object->Method $p1->say(); $p2->run();

5.7. The use of special reference "$this" Now we know how to access members in an object, which is accessed through "Object -> Members", which is a form of accessing members in an object outside the object. So if I want to let the methods in the object access the properties of this object inside the object, or the methods in the object to call other methods of this object, what should we do? Because all members in the object must be called using the object, including calls between internal members of the object, PHP provides me with a reference to this object, $this, and each object has a reference to the object. $this represents this object and completes the call to the internal members of the object. The original meaning of this is "this". In the above example, we instantiate three instance objects $P1, $P2, and $P3. There is one $this each representing objects $p1, $p2, and $p3.

  1. class Person
  2. {
  3. //The following are the member attributes of the person
  4. var $name; //The name of the person
  5. var $***; //The gender of the person
  6. var $ age; //The person's age
  7. //The following is the person's member method
  8. function say() //The method this person can speak
  9. { echo "My name is: ".$this->name." Gender : ".$this->***." My age is: ".$this->age."
  10. ";
  11. }
Copy code

8.Construction method and destruction method Most classes have a special method called a constructor. When an object is created, it will automatically call the constructor, that is, when the new keyword is used to instantiate the object, the constructor will be automatically called.

  The declaration of a constructor is the same as the declaration of other operations, except that its name must be __construct(). This is a change in PHP5. In previous versions, the name of the constructor must be the same as the class name. This can still be used in PHP5, but few people use it now. The advantage of this is that the constructor can be Independent of the class name, there is no need to change the corresponding constructor name when the class name changes. For backward compatibility, if there is no method named __construct() in a class, PHP will search for a constructor method written in php4 with the same name as the class name. Format: function __construct ([parameter]) { ... ... } Only one constructor can be declared in a class, but the constructor will only be called once every time an object is created. This method cannot be called actively, so it is usually used to perform some useful initialization tasks. For example, the corresponding properties are assigned initial values ​​when the object is created.

  1. //Create a human
  2. class Person
  3. {
  4. //The following are the member attributes of the person
  5. var $name; //The name of the person
  6. var $***; //Person Gender
  7. var $age; //Age of a person
  8. //Define a constructor parameter as name $name, gender $*** and age $age
  9. function __construct($name, $***, $age)
  10. {
  11. //The $name passed in through the construction method is assigned an initial value to the member attribute $this->name
  12. $this->name=$name;
  13. //The $*** passed in through the construction method is assigned to The member attribute $this->*** is assigned an initial value
  14. $this->***=$***;
  15. //The $age passed in through the construction method is assigned to the member attribute $this->age Initial value
  16. $this->age=$age;
  17. }
  18. //How this person speaks
  19. function say()
  20. {
  21. echo "My name is: ".$this->name." Gender: ".$this->***." My age is: ".$this->age."
  22. ";
  23. }
  24. }
  25. //Create 3 objects $p1, p2 through the construction method , $p3, respectively pass in three different actual parameters: name, gender and age
  26. $p1=new Person("Zhang San", "Male", 20);
  27. $p2=new Person("Li Si", "Female", 30);
  28. $p3=new Person("王五","Male", 40);
  29. //The following accesses the speaking method in the $p1 object
  30. $p1->say();
  31. / /The following accesses the speaking method in the $p2 object
  32. $p2->say();
  33. //The following accesses the speaking method in the $p3 object
  34. $p3->say();
  35. ?>
Copy the code

The output result is: My name is: Zhang San Gender: Male My age is: 20 My name is: Li Si Gender: Female My age is: 30 My name is: Wang Wu Gender: Male My age is: 40

The opposite of the constructor is the destructor. The destructor is a newly added content of PHP5. There is no destructor in PHP4. The destructor allows you to perform some operations or complete some functions before destroying a class, such as closing files, releasing result sets, etc. The destructor will be deleted when all references to an object are deleted or when the object is explicitly destroyed. When executed, that is, the destructor is called before the object is destroyed in memory. Similar to the name of the constructor, the name of a class's destructor must be __destruct(). The destructor cannot take any parameters. Format: function __destruct ( ) { ... ... }

  1. //Create a human
  2. class Person
  3. {
  4. //The following are the member attributes of the person
  5. var $name; //The person’s name
  6. var $** *; //Person’s gender
  7. var $age; //Person’s age
  8. //Define a constructor method parameter as name $name, gender $*** and age $age
  9. Function __construct ($name, $***, $age)

  10. {
  11. //The $name passed in through the construction method assigns an initial value to the member attribute $this->name
  12. $this->name=$name;
  13. //The $*** passed in through the construction method is assigned an initial value to the member attribute $this->***
  14. $this->***=$***;
  15. //It is passed in through the construction method $age assigns an initial value to the member attribute $this->age
  16. $this->age=$age;
  17. }
  18. //How this person speaks
  19. function say()
  20. {
  21. echo "My name My name is: ".$this->name." Gender: ".$this->***." My age is: ".$this->age."
  22. ";
  23. }
  24. // This is a destructor, which is called before the object is destroyed.
  25. If you provide an interface outside the class, you can provide setting methods and get methods for private attributes outside the class to operate the private attributes. For example: prvate $age; //Private attribute age

    1. function setAge($age) //Provide a public method for setting age externally
    2. {
    3. if($age130) //When assigning values ​​to attributes, in order to avoid Illegal values ​​are set to attributes
    4. return;
    5. $this->age=$age;
    6. }
    7. function getAge() //Provide a public method to get age externally
    8. {
    9. return($this->age);
    10. }
    Copy the code

    The above method is to set and get the value for a member attribute. Of course, you can also use the same method to assign and get the value for each attribute to complete the operation outside the class. Access work. JAVABEAN is the same! ! !

    10. Application of the four methods __set() __get() __isset() __unset()

      Generally speaking, class attributes are always defined as private, which is more in line with realistic logic. However, reading and assigning operations to attributes are very frequent, so in PHP5, two functions "__get()" and "__set()" are predefined to obtain and assign their attributes, and "__isset" to check the attributes. ()" and the method to delete attributes "__unset()". In the previous section, we set and obtained methods for each attribute. PHP5 provides us with special methods for setting and obtaining values ​​for attributes, "__set()" and "__get()". Methods, these two methods do not exist by default, but are manually added to the class. Like the constructor method (__construct()), they will only exist if they are added to the class. You can add these two methods in the following way. Methods, of course, can also be added according to personal style:

    1. //__get() method is used to get private properties

    2. private function __get($property_name)
    3. {
    4.  if(isset($this-> ;$property_name))

    5. {
    6. return($this->$property_name);
    7. }else
    8. {
    9. return(NULL);
    10. }
    11. }
    12. //__set() method is used to set private properties
    13. private function __set ($property_name, $value)
    14. {
    15. $this->$property_name = $value;
    16. }
    Copy code

    __get() method: This method is used to get the private member attribute value. It has one parameter. The parameter is passed in the name of the member attribute you want to get, and the obtained attribute value is returned. This method does not need to be called manually, because we This method can also be made into a private method, which is automatically called by the object when the private property is directly obtained. Because the private properties have been encapsulated, the value cannot be obtained directly (for example: "echo $p1->name" is wrong to obtain directly), but if you add this method to the class, use "echo $p1->name". $p1->name" When such a statement directly obtains the value, it will automatically call the __get($property_name) method, passing the property name to the parameter $property_name, and through the internal execution of this method, the private property we passed in will be returned. value. If the member properties are not encapsulated as private, the object itself will not automatically call this method. __set() method: This method is used to set values ​​for private member attributes. It has two parameters. The first parameter is the name of the attribute you want to set the value for. The second parameter is the value you want to set for the attribute. There is no return. value. This method also does not need to be called manually. It can also be made private. It is automatically called when directly setting the private attribute value. The same private attribute has been encapsulated. If there is no __set() method, it is Not allowed, for example: $this->name='zhangsan', this will cause an error, but if you add the __set($property_name, $value) method to the class, when directly assigning values ​​to private properties, It will be called automatically, passing attributes such as name to $property_name, and passing the value "zhangsan" to be assigned to $value. Through the execution of this method, the purpose of assignment is achieved. If the member properties are not encapsulated as private, the object itself will not automatically call this method. In order not to pass in illegal values, you can also make a judgment in this method.

    1. class Person
    2. {
    3. //The following are the member attributes of the person, which are all encapsulated private members
    4. private $name; //The name of the person
    5. private $***; / /Person’s gender
    6. private $age; //Person’s age
    7. //__get() method is used to obtain private properties
    8. private function __get($property_name)
    9. {
    10. echo "Automatically called when directly obtaining private property values Got this __get() method
    11. ";
    12. if(isset($this->$property_name))
    13. {
    14. return($this->$property_name);
    15. }
    16. else
    17. {
    18. return(NULL);
    19. }
    20. }
    21. //__set() method is used to set private properties
    22. private function __set($property_name, $value)
    23. {
    24. echo "When directly setting the private property value, this __set() method is automatically called Assign a value to a private property
    25. ";
    26.  $this->$property_name = $value;
    27. }
    28. }
    29. $p1=new Person();
    30. //The operation of directly assigning a value to a private property will automatically call __set() Method to assign value
    31. $p1->name="Zhang San";
    32. $p1->***="Male";
    33. $p1->age=20;
    34. //Get the value of the private attribute directly, The __get() method will be automatically called to return the value of the member attribute
    35. echo "Name:".$p1->name."
    36. ";
    37. echo "Gender:".$p1->***."
    38. ";
    39. echo "Age:".$p1->age."
    40. ";
    41. ?>
    Copy code


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
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment