search
HomeBackend DevelopmentPHP TutorialSummary of PHP object knowledge

Summary of PHP object knowledge

May 24, 2018 am 10:02 AM
phpSummarizeKnowledge

This article mainly introduces relevant information summarizing knowledge related to PHP objects. Friends who need it can refer to it

Object passing: One way of saying it is that "PHP objects are passed by reference", which is more accurate. The argument is that aliases (identifiers) are passed, that is, they all store a copy of the same identifier (ID), which points to the real content of the same object.

 <?php
 class A {
   public $foo = 1;
 } 
 
 $a = new A;
 $b = $a;   // $a ,$b都是同一个标识符的拷贝
       // ($a) = ($b) = <id>
 $b->foo = 2;
 echo $a->foo."\n";//2

 $c = new A;
 $d = &$c;  // $c ,$d是引用
       // ($c,$d) = <id>
 
 $d->foo = 2;
 echo $c->foo."\n";//2
 
 $e = new A;
 
 function foo($obj) {
   // ($obj) = ($e) = <id>
   $obj->foo = 2;
 }
 
 foo($e);
 echo $e->foo."\n";//2

•Object copy: Object copy can be completed through the clone keyword. If the original object defines the __clone() method, then _ in the new object The _clone() method will be called after copying, and the __clone() method can be used to modify the value of the copied object's attributes. When an object is copied, a shallow copy will be performed on all properties of the object, but all reference properties will still be references to the original variables.

 <?php
 class SubObject
 {
   static $instances = 0;
   public $instance;
 
   public function __construct()
   {
     $this->instance = ++self::$instances;
   }
 
   public function __clone()
   {
     $this->instance = ++self::$instances;
   }
 }
 
 class MyCloneable
 {
   public $object1;
   public $object2;
 
   function __clone()
   {
     // 强制复制一份this->object, 否则仍然指向同一个对象
     $this->object1 = clone $this->object1;
   }
   
   function cloneTest()
   {
     echo &#39;cloneTest&#39;;
   }
 }
 
 $obj = new MyCloneable();
 
 $obj->object1 = new SubObject();
 $obj->object2 = new SubObject();
 
 $obj2 = clone $obj;
 
 print("Original Object:\n");
 print_r($obj);
 
 print("Cloned Object:\n");
 print_r($obj2);
 echo $obj2->cloneTest().":\n";
 echo (new Reflectionclass($obj2));

Output result of the above example:

Original Object:
MyCloneable Object
(
  [object1] => SubObject Object
    (
      [instance] => 1
    )

  [object2] => SubObject Object
    (
      [instance] => 2
    )

)
Cloned Object:
MyCloneable Object
(
  [object1] => SubObject Object
    (
      [instance] => 3
    )

  [object2] => SubObject Object
    (
      [instance] => 2
    )

)
cloneTest:
Class [ <user> class MyCloneable ] {
 @@ /public/t.php 18-33

 - Constants [0] {
 }

 - Static properties [0] {
 }

 - Static methods [0] {
 }

 - Properties [2] {
  Property [ <default> public $object1 ]
  Property [ <default> public $object2 ]
 }

 - Methods [2] {
  Method [ <user> public method __clone ] {
   @@ /public/t.php 23 - 27
  }

  Method [ <user> public method cloneTest ] {
   @@ /public/t.php 29 - 32
  }
 }
}

•Object traversal: foreach can only Traversing the visible properties of an object cannot traverse its methods, so it is easier to implement; in addition, you can also traverse object properties through methods that implement the Iterator interface or IteratorAggregate interface.

•Type constraints: PHP is a weakly typed language. Type constraints can make programming more standardized and reduce errors; type constraints can not only be used in object definitions, but also in function definitions. Type constraints can specify objects, interfaces, arrays, and callables (closure callbacks). Type constraints are used to ensure that the actual data type is consistent with the prototype definition. If it is inconsistent, a catchable fatal error will be thrown; however, if the default value is NULL, Then the actual parameter can be NULL; type constraints cannot be used for scalar types such as int or string, nor are traits.

•Object serialization and restoration: The function serialize() can convert a string containing a byte stream into a string for easy storage of objects, and the function unserialize() can restore a string into an object. But there is a premise that, regardless of serialization or deserialization, the class definition of the object has been completed, that is, the class (file) needs to be imported first.

•Overloading: PHP's overloading includes attributes and methods. It is more like a formula and does not support common overloading syntax specifications. It is unpredictable and has a wider impact. It uses magic methods (magic methods). methods) to call undefined or invisible class attributes or methods in the current environment. All overloaded methods must be declared public (this should be easier to understand. Others may need you because they are invisible, so you must be visible), and parameters cannot be passed by reference (overloaded methods are unpredictable , probably for security reasons, to prevent variables from being referenced at will). Overloaded properties cannot be used in other language constructs except isset(), which means that when empty() is used on an overloaded property, the overloaded magic method will not be called; to avoid this limitation, Overloaded attributes must be assigned to local variables and then empty() is used. It can be seen that overloaded attributes exist between legal attributes and illegal attributes.

[Attribute overloading]: These methods cannot be declared static. In static methods, these magic methods will not be called.
public void __set (string $name, mixed $value)
When assigning values ​​to inaccessible properties, __set() will be called

public mixed __get (string $name)
When reading the value of inaccessible properties, __get() will be called

public bool __isset ( string $name )
When isset() or empty() is called on an inaccessible property, __isset() will be called

public void __unset ( string $name )
When unset() is called on an inaccessible property, __unset() will be called

Note:
Because of the way PHP handles assignment operations, the return value of __set() will be ignored. Similarly, in the following chain assignment, __get() will not be called:
$a = $obj->b = 8;

[Method overloading]:
public mixed __call ( string $name , array $arguments )
When an inaccessible method is called in an object, __call() will be called

public static mixed __callStatic ( string $name , array $arguments )
When calling an inaccessible method in a static context, __callStatic() will be called

•Static properties and methods: The static keyword is used to define static properties and static methods. Static properties cannot be instantiated. Object-> to access (but static methods can). Static properties can only be initialized as constant expressions, so static properties can be initialized as integers or arrays, but they cannot be initialized as another variable or function return value, nor can they point to an object. You can use a variable to represent a class to dynamically call static properties, but the value of the variable cannot be the keyword self, parent or static.

 class Foo
 {
   public static $my_static = &#39;foo&#39;;
 
   public function staticValue() {
     return self::$my_static;
   }
 }
 
 class Bar extends Foo
 {
   public function fooStatic() {
     return parent::$my_static;
   }
 }
 
 
 print Foo::$my_static . "\n";
 
 $foo = new Foo();
 print $foo->staticValue() . "\n";
 print $foo->my_static . "\n";   // Undefined "Property" my_static 
 
 print $foo::$my_static . "\n";
 $classname = &#39;Foo&#39;;
 print $classname::$my_static . "\n"; // As of PHP 5.3.0
 
 print Bar::$my_static . "\n";
 $bar = new Bar();
 print $bar->fooStatic() . "\n";

•后期静态绑定:static:: 定义后期静态绑定工作原理是存储了上一个“非转发调用”(non-forwarding call)的类名。当进行静态方法调用时,该类名即为明确指定的那个(通常在 :: 运算符左侧部分);当进行非静态方法调用时,即为该对象所属的类。使用 self:: 或者 __CLASS__ 对当前类的静态引用,取决于定义当前方法所在的类;static:: 不再被解析为定义当前方法所在的类,而是在实际运行时计算的,可以用于静态属性和所有方法的调用。

 <?php
 class A
 {
   
   private $proPrivate = "private of A";
   protected $proProtected = "protected of A";
   public $proPublic = "public of A";
   
   private function foo()
   {
     echo $this->proPrivate."\n";
     echo $this->proProtected."\n";
     echo $this->proPublic."\n";
   }
   
   public function test()
   {
     $this->foo();
     static::foo();
   }
 }
 
 class B extends A
 {
  /* foo() will be copied to B, hence its scope will still be A and
   * the call be successful */
 }
 
 class C extends A
 {
   private $proPrivate = "private of C";
   protected $proProtected = "protected of C";
   public $proPublic = "public of C";
   
   private function foo()
   {
     /* original method is replaced; the scope of the new one is C */
     echo "I am C\n";
   }
   
   public function myFoo()
   {
     //parent::foo();
     $this->foo();
   }
 }
 
 echo "Class B:\n";
 $b = new B();
 $b->test();
 echo "\nClass C:\n";
 $c = new C();
 $c->myFoo();
 $c->test();  //fails

上例输出结果:

Class B:
private of A
protected of A
public of A
private of A
protected of A
public of A

Class C:
I am C
private of A
protected of C
public of C 
Fatal error: Uncaught Error: Call to private method C::foo() from context &#39;A&#39; in /public/t.php:19 Stack trace: #0 /public/t.php(54): A->test() #1 {main} thrown in /public/t.php on line 19

•继承:官方文档对继承有这样一段描述“当扩展一个类,子类就会继承父类所有公有的和受保护的方法。除非子类覆盖了父类的方法,被继承的方法都会保留其原有功能”,言下之意似乎私有属性和方法不会被继承;然而上例又告诉我们子类拥有与父类一致的属性和方法,继承就是全盘复制,这才能满足我们对继承编程的需求,如果私有的不能继承,子类就必须自行重新定义,在大多数时候没有必要。另外就是可见性问题,父类的私有属性和方法在子类是不可见的。上例还告诉我们对象实际执行的域要考虑可见性、继承、后期静态绑定机制。

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

PHP表单数据写入MySQL数据库的代码

php基于登陆时间判断实现一天多次登录只积分一次功能

php 三元运算符实例详细介绍

The above is the detailed content of Summary of PHP object knowledge. For more information, please follow other related articles on the PHP Chinese website!

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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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

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.

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.