Home Backend Development PHP Tutorial PHP5 object system_PHP tutorial

PHP5 object system_PHP tutorial

Jul 21, 2016 pm 04:11 PM
php5 object article of series


* This article is a supplement and correction to the "Classes and Objects in PHP5" series of articles. It introduces the overall framework of the PHP5 object system, but some features are not introduced in detail. It is highly recommended to read this article after reading "Classes and Objects in PHP5".



The object system launched by PHP5 is believed to be what everyone is most looking forward to. PHP5 draws on the object model of Java2 and provides relatively powerful object-oriented programming support. Using PHP to implement OO will become easy and natural.



Object passing



PHP5 uses Zend Engine II, and objects are stored in an independent structure Object Store, unlike other general variables That way it is stored in Zval (in PHP4 objects are stored in Zval just like general variables). Only the pointer of the object is stored in Zval rather than the content (value). When we copy an object or pass an object as a parameter to a function, we do not need to copy the data. Just keep the same object pointer and notify the Object Store that this particular object now points to via another zval. Since the object itself is located in the Object Store, any changes we make to it will affect all zval structures holding pointers to the object - manifested in the program as any changes to the target object will affect the source object. .This makes PHP objects look like they are always passed by reference (reference), so objects in PHP are passed by "reference" by default, and you no longer need to use & to declare it like in PHP4.



Garbage collection mechanism

Some languages, most typically C, require you to explicitly ask for memory allocation when you create a data structure. Once you allocate memory, you can store information in variables. At the same time, you also need to release the memory when you are done using the variable, so that the machine can free up memory for other variables and avoid running out of memory.

PHP can automatically manage memory and clear objects that are no longer needed. PHP uses a simple garbage collection mechanism called reference counting. Each object contains a reference counter, and each reference connected to the object increases the counter by one. When reference leaves the living space or is set to NULL, the counter is decremented by 1. When an object's reference counter reaches zero, PHP knows that you no longer need to use this object and releases the memory space it occupies.

For example:

class Person{
}
function sendEmailTo(){
}

$haohappy = new Person( );
// Create a new object: Reference count = 1
$haohappy2 = $haohappy;
// Copy by reference: Reference count = 2
unset($haohappy) ;
// Delete a reference: Reference count = 1
sendEmailTo($haohappy2);
// Pass object by reference:
// During function execution:
// Reference count = 2
// After execution:
// Reference count = 1

unset($haohappy2);
// Delete reference: Reference count = 0 Automatically release memory space

?>



The above are the changes in memory management of PHP5, which may not be of much interest to you. Let’s take a look at the specific differences between the object model in PHP5 and PHP4:



★ New features

★ Improved features



1) ★ Private and Protected Members Private and protected class members (properties, methods)

2) ★ Abstract Classes and Methods Abstract classes and abstract methods

3) ★ Interfaces interface

4) ★ Class Type Hints type indication =

5) ★ final final keyword =

6) ★ Objects Cloning Object copy =

7) ★ Constructors and Destructors Constructors and destructors

8) ★ Class Constants Class constants =

9) ★ Exceptions Exception handling

10) ★ Static member static class member

11) ★__METHOD__ constant __METHOD__ constant =

12) ★ Reflection reflection mechanism



No. 1, 2, 3, 7. 10 Please refer to the "Classes and Objects in PHP5" series at the end of this article. It has been introduced in detail and will not be explained in this article. The 9th point of exception handling and the 12th point of reflection mechanism are relatively rich in content and are not introduced in the article due to space limitations. Please pay attention to the upcoming second issue of the "PHP & More" electronic magazine, which will be specifically introduced in an article.



The following introduces language features 4, 5, 6, 8, and 11:



4) ★ Class Type Hints type indication



As we all know, PHP is a weakly typed language. There is no need to define a variable before using it, and there is no need to declare the data type of the variable. This brings a lot of convenience in programming, but it also brings some hidden dangers, especially when the type of the variable changes. Type instructions were added in PHP5, which can automatically determine the parameter types of class methods during execution. This is similar to RTTI in Java2. Together with reflection, it allows us to control the object very well.





interface Foo {
function a(Foo $foo);
}

interface Bar {
function b(Bar $bar);
}

class FooBar implements Foo, Bar {
function a(Foo $foo) {
// ...
}

function b(Bar $bar) {
// ...
}
}

$a = new FooBar;
$b = new FooBar;

$a->a($b);
$a->b($b);
?>



In a strongly typed language, the types of all variables will be checked at compile time, while in PHP type directives are used to check the type at runtime. If the type of the class method parameter is incorrect, an error message similar to "Fatal error: Argument 1 must implement interface Bar..." will be reported.



The following code:

function foo(ClassName $object) {
// ...
}
?>



is equivalent to:

function foo($object) {
if (!($object instanceof ClassName )) {
die("Argument 1 must be an instance of ClassName");
}
}
?>





5) ★ final final keyword



The final keyword is newly added in PHP5, which can be added before a class or class method. Class methods marked as final cannot be overridden in subclasses. Classes marked as final cannot be inherited, and the methods in them are final by default.

Final method:

class Foo {
final function bar() {
// ...
}
}
?>



Final class:

final class Foo {
// class definition
}

//The following line is wrong
// class Bork extends Foo {}
?>



6) ★ Objects Cloning Object copy

As mentioned earlier in the memory management section, objects are passed by reference by default in PHP5. Objects copied using methods such as $object2=$object1 are related to each other. If we really need to copy an object with the same value as the original and hope that the target object is not related to the source object (passed by value like a normal variable), then we need to use the clone keyword. If you also want to change some parts of the source object while copying, you can define a __clone() function in the class and add operations.



//Object copy
class MyCloneable {
static $id = 0;

function MyCloneable() {
$this->id = self::$id++;
}


/*
function __clone() {
$this->address = "New York";
$this->id = self::$id++;
}
*/
}

$obj = new MyCloneable();

$obj->name = "Hello";
$obj->address = "Tel-Aviv";

print $obj->id . "n";

$obj_cloned = clone $obj;

print $obj_cloned->id . "n";
print $obj_cloned->name . "n";
print $obj_cloned- >address . "n";
?>



The above code copies an identical object.



Then please remove the comment of function __clone() and re-run the program. It will copy an object that is basically the same, but with some properties changed.



8) ★ Class Constants Class constants

You can use the const keyword to define class constants in PHP5.



class Foo {
const constant = "constant";
}

echo "Foo::constant = " . Foo::constant . "n";
?>

















11) ★__METHOD__ constant __METHOD__ constant

__METHOD__ is a new "magic" constant in PHP5 that represents a class method name.
Magic constant is a PHP predefined constant whose value can change. Other existing magic constants in PHP include __LINE__, __FILE__, __FUNCTION__, __CLASS__, etc.

class Foo {
function show() {
echo __METHOD__;
}
}

class Bar extends Foo {
}

Foo::show(); // outputs Foo::show
Bar::show(); // outputs Foo::show either since __METHOD__ is
// compile -time evaluated token

function test() {
echo __METHOD__;
}

test(); // outputs test
?>
(source :Viphot)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314036.htmlTechArticle* This article is a supplement and correction to the "Classes and Objects in PHP5" series of articles, introducing the PHP5 object system The overall framework, but some features are not introduced in detail. It is strongly recommended to read "...
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

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)

How to set up the keyboard boot function on a GIGABYTE motherboard (enable keyboard boot mode on GIGABYTE motherboard) How to set up the keyboard boot function on a GIGABYTE motherboard (enable keyboard boot mode on GIGABYTE motherboard) Dec 31, 2023 pm 05:15 PM

How to set up keyboard startup on Gigabyte's motherboard. First, if it needs to support keyboard startup, it must be a PS2 keyboard! ! The setting steps are as follows: Step 1: Press Del or F2 to enter the BIOS after booting, and go to the Advanced (Advanced) mode of the BIOS. Ordinary motherboards enter the EZ (Easy) mode of the motherboard by default. You need to press F7 to switch to the Advanced mode. ROG series motherboards enter the BIOS by default. Advanced mode (we use Simplified Chinese to demonstrate) Step 2: Select to - [Advanced] - [Advanced Power Management (APM)] Step 3: Find the option [Wake up by PS2 keyboard] Step 4: This option The default is Disabled. After pulling down, you can see three different setting options, namely press [space bar] to turn on the computer, press group

What is the difference between php5 and php8 What is the difference between php5 and php8 Sep 25, 2023 pm 01:34 PM

The differences between php5 and php8 are in terms of performance, language structure, type system, error handling, asynchronous programming, standard library functions and security. Detailed introduction: 1. Performance improvement. Compared with PHP5, PHP8 has a huge improvement in performance. PHP8 introduces a JIT compiler, which can compile and optimize some high-frequency execution codes, thereby improving the running speed; 2. Improved language structure, PHP8 introduces some new language structures and functions. PHP8 supports named parameters, allowing developers to pass parameter names instead of parameter order, etc.

The first choice for CS players: recommended computer configuration The first choice for CS players: recommended computer configuration Jan 02, 2024 pm 04:26 PM

1. Processor When choosing a computer configuration, the processor is one of the most important components. For playing games like CS, the performance of the processor directly affects the smoothness and response speed of the game. It is recommended to choose Intel Core i5 or i7 series processors because they have powerful multi-core processing capabilities and high frequencies, and can easily cope with the high requirements of CS. 2. Graphics card Graphics card is one of the important factors in game performance. For shooting games such as CS, the performance of the graphics card directly affects the clarity and smoothness of the game screen. It is recommended to choose NVIDIA GeForce GTX series or AMD Radeon RX series graphics cards. They have excellent graphics processing capabilities and high frame rate output, and can provide a better gaming experience. 3. Memory power

Convert an array or object to a JSON string using PHP's json_encode() function Convert an array or object to a JSON string using PHP's json_encode() function Nov 03, 2023 pm 03:30 PM

JSON (JavaScriptObjectNotation) is a lightweight data exchange format that has become a common format for data exchange between web applications. PHP's json_encode() function can convert an array or object into a JSON string. This article will introduce how to use PHP's json_encode() function, including syntax, parameters, return values, and specific examples. Syntax The syntax of the json_encode() function is as follows: st

How can I make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! How can I make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! Mar 15, 2024 pm 04:13 PM

1. How can you make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! 1. Activate basic rights and interests: original articles can earn profits by advertising, and videos must be original in horizontal screen mode to earn profits. 2. Activate the rights of 100 fans: if the number of fans reaches 100 fans or above, you can get profits from micro headlines, original Q&A creation and Q&A. 3. Insist on original works: Original works include articles, micro headlines, questions, etc., and are required to be more than 300 words. Please note that if illegally plagiarized works are published as original works, credit points will be deducted, and even any profits will be deducted. 4. Verticality: When writing articles in professional fields, you cannot write articles across fields at will. You will not get appropriate recommendations, you will not be able to achieve the professionalism and refinement of your work, and it will be difficult to attract fans and readers. 5. Activity: high activity,

Digital audio output interface on the motherboard-SPDIF OUT Digital audio output interface on the motherboard-SPDIF OUT Jan 14, 2024 pm 04:42 PM

SPDIFOUT connection line sequence on the motherboard. Recently, I encountered a problem regarding the wiring sequence of the wires. I checked online. Some information says that 1, 2, and 4 correspond to out, +5V, and ground; while other information says that 1, 2, and 4 correspond to out, ground, and +5V. The best way is to check your motherboard manual. If you can't find the manual, you can use a multimeter to measure it. Find the ground first, then you can determine the order of the rest of the wiring. How to connect motherboard VDG wiring When connecting the VDG wiring of the motherboard, you need to plug one end of the VGA cable into the VGA interface of the monitor and the other end into the VGA interface of the computer's graphics card. Please be careful not to plug it into the motherboard's VGA port. Once connected, you can

Xiaomi 15 series full codenames revealed: Dada, Haotian, Xuanyuan Xiaomi 15 series full codenames revealed: Dada, Haotian, Xuanyuan Aug 22, 2024 pm 06:47 PM

The Xiaomi Mi 15 series is expected to be officially released in October, and its full series codenames have been exposed in the foreign media MiCode code base. Among them, the flagship Xiaomi Mi 15 Ultra is codenamed "Xuanyuan" (meaning "Xuanyuan"). This name comes from the Yellow Emperor in Chinese mythology, which symbolizes nobility. Xiaomi 15 is codenamed "Dada", while Xiaomi 15Pro is named "Haotian" (meaning "Haotian"). The internal code name of Xiaomi Mi 15S Pro is "dijun", which alludes to Emperor Jun, the creator god of "The Classic of Mountains and Seas". Xiaomi 15Ultra series covers

Glodon Software's computer configuration recommendations; Glodon Software's computer configuration requirements Glodon Software's computer configuration recommendations; Glodon Software's computer configuration requirements Jan 01, 2024 pm 12:52 PM

Glodon Software is a software company focusing on the field of building informatization. Its products are widely used in all aspects of architectural design, construction, and operation. Due to the complex functions and large data volume of Glodon software, it requires high computer configuration. This article will elaborate on the computer configuration recommendations of Glodon Software from many aspects to help readers choose a suitable computer configuration processor. Glodon Software requires a large amount of data calculation and processing when performing architectural design, simulation and other operations. Therefore, the requirements for the processor are higher. It is recommended to choose a multi-core, high-frequency processor, such as Intel i7 series or AMD Ryzen series. These processors have strong computing power and multi-thread processing capabilities, and can better meet the needs of Glodon software. Memory Memory is affecting computing

See all articles