Some features of PHP objects

Source: Internet
Author: User
Tags shallow copy

Class person{    private $name;    Private $age = 2;    Public function __construct ($name, $age)    {        $this->name = $name;        $this->age = $age;    }} $p 1 = new person (' Gxw ', ' n '), $p 2 = new Person (' Gxw ', ' n '), if ($p 1 = = $p 2) {    echo "P1 = = P2";} else{    echo "P1! = p2";}//echo p1 = p1if ($p 1 = = = $p 2) {    echo "p1 = P2";} else{    echo "P1! = p2";}//echo p1! = P2

' = = ' is used to determine whether all properties of two object instances are equal.

the ' = = = ' is used to determine whether two variables are references to the same object.

$p 3 = $p 1;if ($p 3 = = = $p 1) {    echo ' p3 = = P1 ';} else{    echo ' P3! = P1 ';} echo ' P3 = = P1 ' $p 3->name = ' www '; if ($p 3 = = $p 1) {    echo ' p3 = = P1 ';} else{    echo ' P3! = P1 ';}//echo P3==P1

P3 is a reference to P1, the change P3 also affects P1, which can be said to P3 as a shallow copy of P1. This situation often occurs in function

$p 1 = new person (' Gxw ', ' n '), function change ($tmp) {    $tmp->name = ' tmp ';} Change ($p 1), echo $p 1->name;//echo tmp$str = ' Hello ', function zero ($tmp) {    $tmp = ';} Zero ($STR); Echo $str; echo Hello

  

It can be seen that PHP has a special handling of function parameters, which is passed as a reference when passing a Class object instance. In the case of string types and other underlying types, copy is performed first.

Make deep copies of objects with the Clone keyword (note is a keyword, not a method)

$p 4 = clone $p 1; $p 4->name = ' Hello '; if ($p 1 = = $p 4) {    echo ' p1 = = P4 ';} else{    echo ' P1! = P4 ';}//echo p1! = P4

See P1 's name is not changed because of P4 's name, indicating P4 is a deep copy of P1.

We can also overload the Clone method to achieve some specific replication effects.

Some features of PHP objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.