search
HomeBackend DevelopmentPHP TutorialPHP5 object system_PHP tutorial


* 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
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 Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

Video Face Swap

Video Face Swap

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

Hot Tools

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version