Home Backend Development PHP Tutorial Learning classes in php5_PHP tutorial

Learning classes in php5_PHP tutorial

Jul 21, 2016 pm 03:53 PM
php php5 code copy study constant of

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 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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles