Home > Backend Development > PHP Tutorial > php classes and objects

php classes and objects

伊谢尔伦
Release: 2016-11-23 14:24:44
Original
1547 people have browsed it

1. Introduction

Since PHP 5, the object model has been completely rewritten to get better performance and more features. This is the biggest change since PHP 4. PHP 5 has a complete object model.
New features in PHP 5 include access control, abstract and final classes and methods, additional magic methods, interfaces, object copying and type constraints.
PHP treats objects the same way as references and handles, that is, each variable holds a reference to the object rather than a copy of the entire object.

2. Basic concepts

1.class

The definition of each class starts with the keyword class, followed by the class name, followed by a pair of curly brackets, which contains the definition of the attributes and methods of the class.
The class name can be any legal tag that is not a PHP reserved word. A legal class name starts with a letter or underscore, followed by a number of letters, numbers, or underscores. Expressed as a regular expression: [a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*.
A class can contain its own constants, variables (called "properties") and functions (called "methods").
Example #1 Simple class definition

<?php
    class SimpleClass
    {
        //声明属性
        public $var = &#39;1&#39;;
        //声明方法
        public function displayVar(){
            echo $this->var;
        }
    }
?>
Copy after login

When a method is called inside a class definition, there is a pseudo variable $this available. $this is a reference to the calling object (usually the object the method belongs to, but possibly another object if called statically from a second object).
Example #2 Example of $this pseudo variable

<?php
    class A
    {
        function foo()
        {
            if(isset($this)){
                echo &#39;$this is defined (&#39;;
                echo get_class($this);
                echo &#39;)<br>&#39;;
            }else{
                echo &#39;$this is not defined.<br>&#39;;
            }
        }
    }
    class B
    {
        function bar()
        {
            //如果开启了E_STRICT这一行会有警告提示
            A::foo();
        }
    }
    $a = new A();
    $a -> foo();
    //如果开启了E_STRICT这一行会有警告提示
    A::foo();
    $b = new B();
    $b -> bar();
    //如果开启了E_STRICT这一行会有警告提示
    B::bar();
?>
Copy after login

Output result:

$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.

2.new

To create an instance of a class, you must use the new keyword. A new object is always assigned a value when it is created, unless the object defines a constructor and an exception is thrown on error. Classes should be defined before being instantiated (and in some cases this is necessary).
If new is followed by a string containing the class name, an instance of the class is created. If the class belongs to a namespace, its full name must be used.
Example #3 Create an instance

<?php
    $instance = new SimpleClass();
    //也可以这样做:
    $className = "Foo";
    $instance = new $className(); //Foo()
?>
Copy after login

Within the class definition, you can use new self and new parent to create new objects.
When assigning an already created instance of an object to a new variable, the new variable will access the same instance as if assigned with the object. This behavior is the same as when passing an instance to a function. You can use cloning to create a new instance of an already created object.
Example #4 Object assignment

include_once(&#39;class1.php&#39;);
$instance = new SimpleClass();
$assigned = $instance;
$reference = & $instance;
$instance -> var = &#39;$assigned will have this value&#39;;
$instance = null; //$instance和$reference变成null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
Copy after login

The output result is:

NULL
NULL
object(SimpleClass)#1 (1) { ["var"]=> string(30) "$assigned will have this value" }

PHP 5.3.0 introduces two new methods to create an instance of an object:

c

lass Test
{
    static public function getNew()
    {
        return new static;
    }
}
class Child extends Test
{}
$obj1 = new Test();
$obj2 = new $obj1;
var_dump($obj1 !== $obj2);
$obj3 = Test::getNew();
var_dump($obj3 instanceof Test);
$obj4 = Child::getNew();
var_dump($obj4 instanceof Child);
Copy after login

Output result:

bool(true)
bool(true)
bool(true)

3. extends

A class can inherit the methods and properties of another class using the extends keyword in the declaration. PHP does not support multiple inheritance. A class can only inherit one base class (single inheritance like Java).
Inherited methods and properties can be overridden by redeclaring them with the same name. But if the parent class uses final when defining a method, the method cannot be overridden. Overridden methods or properties can be accessed through parent:: .
When overriding a method, the parameters must be consistent otherwise PHP will issue an E_STRICT level error message. The exception is constructors, which can take different parameters when overridden.
Example #6 Simple class inheritance:

class ExtendClass extends SimpleClass
{
    //重写父类的方法
    function displayVar()
    {
        echo "Extending class<br>";
        parent::displayVar();
    }
}
$extended = new ExtendClass();
$extended -> displayVar();
Copy after login

Output result:

Extending class
1

4.::class

Since PHP 5.5, the keyword class can also be used for class name resolution. Using ClassName::class you can get a string containing the fully qualified name of the class ClassName . This is especially useful for classes that use namespaces.
Example #7 Class name analysis

namespace NS{
    class ClassName{}
    echo ClassName::class;
}
Copy after login

Output result:

NSClassName


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template