Classes and Objects-PHP manual notes

Source: Internet
Author: User
Tags export class php class php script traits

Original: Classes and objects-PHP manual notes

Basic concepts

PHP treats objects in the same way as references and handles, where each variable holds a reference to the object, not a copy of the entire object.

When a new object is created, the object is always assigned, unless the object defines the constructor and throws an exception when an error occurs. The class should be defined before it is instantiated.

When you create an object, if the class belongs to a namespace, you must use its full name.

Within a class definition, you can use new self and new parent create objects.

<?php $instance = new stdClass();$assigned = $instance;$reference = & $instance;$instance->var = '$assigned will have this value.';$instance = null;var_dump($instance);var_dump($reference);var_dump($assigned);

The output of this code is as follows, which is why?

nullnullobject(stdClass)[1]  public 'var' => string '$assigned will have this value.' (length=31)

PHP 5.3 Introduces two new methods to create an instance of an object, which can be created using the following method.

<?php class Test {static public function getNew() {return new static;}}class Child extends Test {}$obj1 = new Test();$obj2 = new $obj1;var_dump($obj1 !== $obj2);  // true$obj3 = Test::getNew();var_dump($obj3 instanceof Test);  // true$obj4 = Child::getNew();var_dump($obj4 instanceof Child);  // truevar_dump($obj1 == $obj2);  // true

PHP does not support multiple inheritance, inherited methods and properties can be re-declared by the same name is overwritten, note that the parameters must be consistent , of course, except for the constructor function. However, if the parent class defines the method final , the method cannot be overwritten. You can access parent:: overridden methods and properties, parent:: access only constants in the parent class const , and cannot access variables.

<?php class A {private $name = 'A';const conname = 'A';public function getName() {return $this->name;}}class B extends A {private $name = 'B';const conname = 'B';public function getName() {return $this->name;}public function getParent() {return parent::conname;}}class C extends B {private $name = 'C';const conname = 'C';public function getName() {return $this->name;}public function getParent() {return parent::conname;}}$a = new A;var_dump($a->getName());  // A$b = new B;var_dump($b->getName());  // Bvar_dump($b->getParent());  // A$c = new C;var_dump($c->getName());  // Cvar_dump($c->getParent());  // B

Since PHP 5.5, keywords class can also be used for the parsing of class names. Using ClassName::class you can get a string that contains the ClassName fully qualified name of the class.

<?php namespace NS {class ClassName {}echo ClassName::class;  // NS\ClassName}
Property

property, which is the variable member of the class. A variable in a property can be initialized, but the initialized value must be a constant. The constant here is that the PHP script can get its value at compile time without relying on the information at run time to evaluate it.

In the member method of the class, access to the static property is used to access the non-static property $this->property self::$property . Use keywords when static property declarations static .

Class constants

Symbols and access control keywords are not required when defining constants $ .

You can also define constants in the interface (interface).

Auto Load Class

When writing object-oriented applications, it is common for each class to define a résumé for a php source file. When a file needs to call these classes, you need to write a long list of included files at the beginning of the file. In fact, it is not necessary to define a __autoload() function that will be called automatically when trying to use a class that has not yet been defined.

The manual tip says, spl_autoload_register() provides a more flexible way to implement automatic loading of classes, which is seen later.

Automatically loads the CLI interaction mode that is not available for PHP, which is the command-line mode.

There may be dangerous characters in the user input, at least at the __autoload() time of validation.

Classes can be loaded automatically in the following way.

<?php function __autoload($class_name) {require_once $class_name.'.php';}$obj1 = new MyClass1();$obj2 = new MyClass2();

For exception handling, see later.

Constructors and destructors

PHP 5 allows the developer to define a method as a constructor in a class, and the constructor does not support overloading.

If a constructor is defined in a subclass, the constructor of the parent class is not implicitly invoked, otherwise it inherits from the parent class as if it were a normal class method (as long as it is not defined private ). To execute the constructor of the parent class, you need to call it in the subclass constructor parent::__construct() .

Unlike other methods, __construct() __construct() You can override a parent class when it has different parameters.

From PHP 5.3.3, in a namespace, a method with the same name as the class name is no longer a constructor.

Destructors are executed when all references to an object are deleted or objects are displayed for destruction. Destructors are called even when they are run with the exit() terminate script.

Attempting to throw an exception in a destructor will result in a fatal error.

Access control

The class attribute must be defined as public, protected, private, and cannot be omitted from the keyword. If a method in a class does not have access control keywords set, the method defaults to public.

Objects of the same class, even if they are not the same instance, can access each other's private and protected members. The sample program is as follows.

<?php Class Test {private $foo;public function __construct($foo) {$this->foo = $foo;}private function bar() {echo 'Accessed the private method.';}public function baz(Test $other) {$other->foo = 'hello';var_dump($other->foo);$other->bar();}}$test = new Test('test');$test->baz(new Test('other'));
Object inheritance

If a class extends another, the parent class must be declared before the child class.

Scope resolution Operators

The scope resolution operator, simply a pair of colons, can be used to access static members, class constants, and to invoke properties and methods in the parent class.

Use the class name when referencing these items outside of the class definition.

Static

staticYou can use keywords to define static methods and properties, or to define static variables and late static bindings. Declaring a class property or method as static can be accessed directly without instantiating the class.

Static properties cannot be accessed through an object that is instantiated by a class, but static methods can.

If no access control is specified, the properties and methods are public by default.

Invoking a non-static method with a static method results in a E_STRICT level of error.

Abstract class

PHP 5 supports abstract classes and abstract methods. If there is an abstract method in the class, the class must be declared abstract.

Abstract classes cannot be instantiated. An abstract method simply declares its invocation method (parameter) and cannot define its specific function implementation. When inheriting an abstract class, the child class must define all the abstract methods in the parent class, and the access control for those methods must be as loose as the parent class.

Methods must be called in a matching manner. However, the subclass defines an optional parameter, and the declaration of the parent abstract method does not, and the declaration does not conflict. This also tries a constructor with PHP 5.4. You can define optional parameters in a subclass that do not exist in the signature of the parent class.

<?php abstract class AbstractClass {abstract protected function prefixName($name);}class ConcreteClass extends AbstractClass {public function prefixName($name, $separator = ', ') {if($name === "Pacman") {$prefix = 'Mr';} elseif($name === 'Pacwoman') {$prefix = "Mrs";} else {$prefix = '';}return "$prefix $separator $name  ";}}$class = new ConcreteClass;echo $class->prefixName('Pacman');echo $class->prefixName('Pacwoman');
Object interface

Have heard of the interface, has been useless. Using interfaces, you can specify which methods a class must implement, but you do not need to define the specifics of those methods, meaning that all methods defined in the interface are empty. All methods defined in the interface must be public, which is the attribute of the interface.

Interfaces can also inherit multiple interfaces, separated by commas, using extends operators. All methods defined in the interface must be implemented in the class, or an error will occur. To implement an interface, use the implements operator. A class can implement multiple interfaces, separated by commas. When implementing multiple interfaces, the methods in the interface cannot have duplicate names. Class to implement an interface, it must be in a way that is exactly the same as the method defined in the interface.

Constants can also be defined in an interface. Interface constants and class constants are used exactly the same, but cannot be overridden by subclasses or sub-interfaces.

Traits

Starting with PHP 5.4.0, you can use the traits implementation code reuse. Traits is a code reuse mechanism that is prepared for PHP-like single-inheritance languages. Trait cannot be instantiated by itself. It adds a combination of horizontal features to traditional inheritance.

Precedence is the method from which the member of the current class overrides the trait, and trait overrides the inherited method.

Separated by commas, multiple trait are listed in the use declaration and can be inserted into a class. If two trait are inserted with a method of the same name, if the conflict is not explicitly resolved, a fatal error will be generated, and in order to resolve the conflict, use the insteadof operator to indicate which of the conflicting methods are used, and this method only allows other methods to be excluded. The as operator can introduce one of the conflicting methods with another name (alias).

<?php trait A {public function smallTalk() {echo 'a';}public function bigTalk() {echo 'A';}}trait B {public function smallTalk() {echo 'b';}public function bigTalk() {echo 'B';}}class Talker {use A, B {B::smallTalk insteadof A;A::bigTalk insteadof B;B::bigTalk as talk;}}$t = new Talker();$t->smallTalk();  // b$t->bigTalk();  // A$t->talk();  // B

Using the as operator can also be used to adjust the access control of the method, or to give the method a change of access control alias, the original method of access control rules have not changed.

<?php trait HelloWorld {public function sayHello() {echo 'Hello World.';}}class MyClass1 {use HelloWorld {sayHello as protected;}}class MyClass2 {use HelloWorld {sayHello as private myPrivateHello;}}

Just as a class can be used trait , multiple trait can be combined into one trait .

In order to impose mandatory requirements on the classes used, trait supports the use of abstract methods.

<?php trait Hello {public function sayHelloWorld() {echo 'Hello ' . $this->getWorld();}abstract public function getWorld();}class MyHelloWorld {private $world;use Hello;public function getWorld() {return $this->world;}public function setWorld($val) {$this->world = $val;}}$c = new MyHelloWorld;$c->setWorld('world');$c->sayHelloWorld();

If trait a property is defined, the class will not be able to define properties of the same name, or an error will result.

Overload

The overloads provided by PHP refer to the dynamic creation of class properties and methods, unlike most other object-oriented languages. By magic Method. Overloaded methods are called when an inaccessible property or method is used. All overloaded methods must be declared as public .

Use __get() , __set() , __isset() , to __unset() perform property overloading, as shown below.

<?php class PropertyTest {private $data = array();public $declared = 1;private $hidden = 2;public function __set($name, $value) {echo "Setting $name to $value. " . '<br>';$this->data[$name] = $value;}public function __get($name) {echo "Getting $name. <br>";if(array_key_exists($name, $this->data)) {return $this->data[$name];}return null;}public function __isset($name) {echo "Is $name set? <br>";return isset($this->data[$name]);}public function __unset($name) {echo "Unsetting $name. <br>";unset($this->data[$name]);}}$obj = new PropertyTest;$obj->a = 1;var_dump($obj->a);var_dump(isset($obj->a));unset($obj->a);var_dump(isset($obj->a));var_dump($obj->declared);var_dump($obj->hidden);

The output results are as follows:

Setting a to 1. Getting a. int 1Is a set? boolean trueUnsetting a. Is a set? boolean falseint 1Getting hidden. null

Called when an inaccessible method is called in an object __call() . Called when a non-accessible method is invoked in a static manner __callStatic() . The parameter is the name of the calling method and an enumerated array, which is case sensitive.

Use __call() and __callStatic() to overload the method, for example, below.

<?php class MethodTest {public function __call($name, $arguments) {echo "Calling object method $name " . implode(', ', $arguments) . '<br>';}public static function __callStatic($name, $arguments) {echo "Calling static method $name " . implode(', ', $arguments) . '<br>';}}$obj = new MethodTest;$obj->runTest('in object context');MethodTest::runTest('in static context');
Traversing objects

Objects can be traversed using a list of cells, for example with foreach statements. All visible properties By default will be used for traversal.

<?php class MyClass {public $var1 = 'value 1';public $var2 = 'value 2';public $var3 = 'value 3';private $var4 = 'value 4';protected $var5 = 'value 5';}$obj = new MyClass;foreach($obj as $key => $value) {echo "$key => $value <br>";}

Sample program 2 implements an object traversal of the iterator interface, and example 3 iterates through the object by implementing Iteratoraggregate.

Magic method

PHP __ retains all class methods that begin with (two underscores) as a magic method. When defining a class method, it is recommended that you do not prefix it except for magic methods __ .

The magic methods that have been encountered before are:,,,,,, __construct() __destruct() __call() __callStatic() __get() __set() __isset() , __unset() . The following will be introduced:,,,, __sleep() __wakeup() __toString() __invoke() __set_state() , __clone() and __debugInfo() .

__sleepAnd do __wakeup not know exactly what to do with, the sample program gives an example of a database connection.

__toStringmethod is used to respond to how a class is treated as a string. This method must return a string and cannot throw an exception in the method. If an object with an undefined __toString() method is converted to a string, an error is generated.

The method is called when an attempt is made to invoke an object in a way that invokes a function __invoke() .

When var_export() the export class is called, __set_state() it is called.

When called var_dump() , __debugInfo it is called. PHP 5.6 Newly added, no suitable environment can not be tested.

Final

If a method in the parent class is declared final , the child class cannot overwrite the method. If a class is declared final , it cannot be inherited . Properties cannot be defined as final only classes and methods can be defined as final .

Object replication

In most cases, we don't need to replicate an object completely, but sometimes it does. Object replication can be clone done by keyword. This replication is implemented by invoking the object's __clone() methods, but the methods in the object __clone() cannot be called directly.

Object comparison

The comparison operator is true if the == properties and property values of two objects are equal, and two objects are instances of the same class.

Objects that inherit two subclasses of a base class are not equal == .

<?php class Base {}class A extends Base {}class B extends Base {}$a = new A;$b = new B;var_dump($a == $b);  // false

===the true condition of the strict equality operator is that two object variables must point to the same instance of a class (that is, the same object).

Type constraints

A type constraint is a parameter to a function that specifies that it must be an object, an interface, an array, or a callable type. However, type constraints cannot be used for scalar types, such as int or, and are string traits not allowed. Type constraint allowable NULL value.

Late static binding

Late static binding, used to refer to a statically invoked class within an inherited scope.

A forward call refers to a static call made in the following ways: self:: , parent:: static:: as well forward_static_call() .

Late static binding works by storing the class name of the last non-forwarded call.

When a static method call is made, the class name is the one explicitly specified, and the class to which the object belongs when a non-static method call is made.

The use self:: or __CLASS__ static reference to the current class depends on the class in which the current method is defined.

<?php class A {public static function who() {echo __CLASS__;}public static function test() {self::who();}}class B extends A {public static function who() {echo __CLASS__;}}B::test();  // AB::who();  // B

static::the class that was originally called by the runtime is represented by a keyword, which is how late static binding is used. As shown in the following program, that test() is, the class referenced at the time of invocation is B instead A .

<?php class A {public static function who() {echo __CLASS__;}public static function test() {static::who();}}class B extends A {public static function who() {echo __CLASS__;}}B::test();  // BB::who();  // B

Example 2 gives a non-static environment to use static:: .

The parsing of the late static bindings will continue until a fully resolved static call is made. Additionally, if a static call parent:: is used or self:: the call information is forwarded.

<?php class A {public static function foo() {static::who();}public static function who() {echo __CLASS__;}}class B extends A {public static function test() {A::foo();parent::foo();self::foo();}public static function who() {echo __CLASS__;}}class C extends B {public static function who() {echo __CLASS__;}}C::test();  // ACC

So the question comes, so why is that?

Objects and references

By default, objects are passed by reference. But this is not entirely true, in fact two object variables are not reference relationships, but they all keep a copy of the same identifier, which points to the real content of the same object.

Serialization of objects

All values in PHP can be represented by using serialize() a function to return a string containing a stream of bytes. unserialize()function to re-convert the string into its original value.

Serializing an object saves all variables of the object, but does not save the object's methods, only the name of the class is saved. In order to be able to unserialize() an object, the class of this object must already be defined. Serializing an object in an application for later use strongly recommends that the entire application contain the definition of the object's class.

(End of full text)

Classes and Objects-PHP manual notes

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.