search
HomeBackend DevelopmentPHP TutorialLearning classes in php5_PHP tutorial

Copy code The code is as follows:

public $name = 'value'; // Properties
public function name() // Methods
{ echo 'value';
}   
}
?>  



Among them, properties and methods can use three different keywords: public, protected, and private to further expand the scope of properties and methods. The difference is that for attributes and methods with the private keyword, only methods in the class in which they are located can be called; for attributes and methods with the protected keyword, in addition to themselves, methods in their own parent class and subclass can also be called. ; Properties and methods with the public keyword can be called from the object after instantiation. The biggest advantage of this is that it adds some descriptive features to all properties and methods, making it easier to organize and organize the code structure. The const keyword is skipped first and discussed together with static later.
The static keyword is another type of keyword different from public, protected, private (so it can be used in combination with public, protected, private):




Copy code
The code is as follows: echo 'value'; } }
} "::" symbol call, combined with public, protected, private, can also distinguish the permissions of the call, but it is usually paired with public. The constant keyword const mentioned earlier should be of public static type, so it can only be Constants are called in the form of self::NAME, TEST::NAME, and the subsequent __construct, __destruct and other methods are static.

In the structural part of the class, the last two keywords introduced are abstract and final. The abstract keyword indicates that this class must be overridden by its subclasses, and the final keyword indicates that this class must not be overridden by its subclasses. Subclass override, the functions of these two keywords are exactly opposite. Methods with abstract are called abstract methods, and classes with abstract methods are called abstract classes. This will be introduced later. There are two main ways to use the

class: There are two main ways to use the

class, one is to use the new keyword, the other is to use the "::" symbol:

PHP code


Copy code

The code is as follows:


class TEST
{
public static function name()                                                   
$test->name();
//Method 2: Use the "::" symbol TEST::name(); ?>

(1): Use the new keyword to become an instantiation. The $test above is an object generated by instantiating the TEST class. $test->name() is called the name of the $test object. method.
(2): When using the new keyword to use a class, you can use $this to refer to the class itself.
(3): The prerequisite for using the "::" symbol is that the method must have the static keyword. When using the new keyword, the method being called must have the public keyword (if a method does not have the public keyword , protected, private, the default is public)
(4): The same class can be instantiated into multiple different objects through the new keyword, but they are isolated from each other; " When the ::" symbol is used, the method is shared between multiple uses:

PHP code
Copy code Code As follows:

$this ->name = $this->name + 1;
} }
}

$test1 = new TEST1;
$test2 = new TEST1;
$test1-> ;name(); //$name1 == 1
$test2->name(); //$name1 == 1

/*---------- ----------------------------------*/ 

class TEST2 

public static $name = 0;
public static function name()
{ TEST2::$name = TEST2::$name + 1;

} 🎜>} 
TEST2::name(); // $name == 1
TEST2::name(); // $name == 2
?>

Class relationship:

The relationship between classes mainly includes abstraction, interface and inheritance:

PHP code


Copy code

The code is as follows :


abstract class TEST1 // Abstract                                                                            🎜>class TEST2 extends TEST1 implementations TEST3 // Inheritance 
 public function name1() 
 {                                            >} 

interface TEST3 // Interface 

public function name2(); 

?> 



(1) Classes with the abstract keyword are abstract classes, and methods with the abstract keyword are abstract methods. Abstract methods in abstract classes must be overridden in subclasses.
(2) A class with the interface keyword is an interface. Interfaces are not allowed to implement any methods. All methods in the interface must be overridden in subclasses.
(3) Those with the words classA extends classB or classA implements classB are inheritance. extends means inheriting another class, and implements means inheriting another interface. Only one class can be extended at a time, but multiple interfaces can be implemented.
(4) Abstract classes, interfaces, and ultimately inherited and implemented methods must be public.

During the inheritance process, the subclass will overwrite the method of the parent class with the same name. At this time, if you need to call the method of the parent class in the subclass, you can use the parent keyword or the class name plus ":: "Symbol call:

PHP code
Copy code The code is as follows:

class TEST1 extends TEST2
{ public function name()
{ echo parent::name2(); echo TEST2::name2 (); 
 } 

class TEST2 

public function name2() 
 { 
 echo 'value2'; 
 } 

$test = new TEST1; 
$test->name();
?>



Here is another explanation of the role of the "::" method in the class. One role is when there is no instantiation Under certain circumstances, call constants (actually, it can also be understood as static), static properties and methods, and the other is to establish a convenient calling channel inside the class through self, parent and class name.

The relationship between objects is mainly "==" equal, "===" all equal, not equal and clone: ​​

PHP code
class TEST                                                                                              🎜>$test2 = new TEST;
$test3 = $test1;
echo $test1 == $test2 ? true : false; // true
echo $test1 == $test3 ? true : false; // true
echo $test2 == $test3 ? true : false; // true
echo $test1 === $test2 ? true : false; // false
echo $test1 === $test3 ? true : false ; // true
echo $test2 === $test3 ? true : false; // false
?>

(1) As long as two classes have the same attributes and methods, that is "==" equals.
(2) The two classes must point to the same object to be equal to "===".

Clone is special. In the above example, the process of $test3 = $test1 does not give $test3 a copy of the $test1 object, but makes $test3 point to $test1. If you must To obtain a copy of $test1, you must use the clone keyword:

PHP code



Copy code

The code is as follows:


$test3 = clone $test1; 
?> 



Hooks of class:

__autoload:
is a function name and the only hook used outside the class. When instantiating an object, if it is not preloaded class, this hook will be called.

__construct
When a class is instantiated, the hook that is called can perform some initialization operations.

__destruct
Hook that is called when the class is destroyed.

__call
When the object tries to call a method that does not exist, the hook is called

__sleep
When the serialize() function is used to serialize a class This hook will be called

__wakeup
When the unserialize() function is used to deserialize a class, this hook will be called

__toString
When an object When it will be converted into a string, this hook will be called (such as echo)

__set_state
When the var_export() function is called to operate a class, this hook will be called

__clone
When you use the clone keyword to copy a class, this hook will be called

__get
When you get the attribute value in a class, this hook will be called

__set
When setting the attribute value in a class, this hook will be called

__isset
When using the isset() function to determine the attribute value in the class, This hook

__unset
will be called when using the unset() function to destroy an attribute value. Tips for the

class:

in the instance When talking about a class, you can use this form to pass parameters to the __construct hook:

PHP code
Copy code The code is as follows:

class TEST ​🎜> }  
}

$test = new TEST('value'); // Display value
?>



The foreach() function can be used to test classes or objects The properties in are traversed. When traversing, the status of public, protected, and private will be judged first and displayed:

PHP code



Copy code

The code is as follows:
class TEST 🎜> public $property3 = 'value3'; ;
public function name()
{ foreach($this as $key => $value)
{
print "$key => $valuen";                                                  🎜> {                                                                                                                                    When passing parameters through the method, you can forcefully determine the parameters. Only arrays and objects are supported here:

PHP code



Copy code

The code is as follows:

class TEST1
{
public function name(TEST2 $para)
{ }
>} 

class TEST2 
{ 

} 

$test2 = new TEST2; 
$test1 = new TEST1; 

$test1->name('value '); // An error will be reported because this parameter must be an object after instantiation of TEST2.
$test1->name($test1); // No error will be reported.
?>

PHP4-compatible syntax:
PHP5 classes are backward compatible with PHP4. These PHP4-era syntaxes have also been inherited, but they are not recommended for use in a PHP5 environment.

(1) Using the var default attribute will automatically convert it to public.

(2) Use the class name as the constructor. If there is no __construct constructor, it will look for a function with the same name as the class as the constructor.




http://www.bkjia.com/PHPjc/318761.html

www.bkjia.com

http: //www.bkjia.com/PHPjc/318761.htmlTechArticleCopy the code as follows: ?php classTEST { constNAME='value';//Constant public$name='value ';//Attribute publicfunctionname()//Method { echo'value'; } } ? Among them, the attributes and methods are...
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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

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

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment