PHP Classes and objects

Source: Internet
Author: User

First, Introduction

The object model has been completely rewritten since PHP 5 for 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 classes and final classes and methods, additional magic methods, interfaces, object copying, and type constraints.
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.

Ii. Basic Concepts

1.class

Each class's definition begins with the keyword class followed by the class name followed by a pair of curly braces containing the definition of the class's properties and methods.
The class name can be a legitimate label for any non-PHP reserved word. A legal class name begins with a letter or underscore followed by several letters, numbers, or underscores. expressed as a regular expression: [a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*.
A class can contain constants that belong to itself, variables (called "Attributes"), and functions (known as "methods").
Example #1 a simple class definition

<?php    class Simpleclass    {        //Declaration Property public        $var = ' 1 ';        Declaring a method public        function Displayvar () {            echo $this->var;        }    }? >

When a method is called inside a class definition, there is an available pseudo-variable $this. $this is a reference to the calling object (usually the object that the method is dependent on, but it may be another object if it is called from a second object statically).
Examples of Example #2 $this pseudo-variables

<?php    class A    {        function foo ()        {            if (isset ($this)) {                echo ' $this is defined (';                echo Get_class ($this);                echo ') <br> ';            } else{                Echo ' $this is not defined.<br> ';            }        }    }    Class B    {        function bar ()        {            ///If E_strict is turned on this line will have a warning            a::foo ();}    }    $a = new A ();    $a foo ();    If you open the E_strict this line will have a warning    a::foo ();    $b = new B ();    $b bar ();    If you open the E_strict this line will have a warning    b::bar (); >

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. 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 (in some cases it must).
If after new is followed by a string containing the class name, an instance of the class is created. If the class belongs to a namespace, you must use its full name.
Example #3 Create an instance

<?php    $instance = new Simpleclass ();    You can also do this:    $className = "Foo";    $instance = new $className (); Foo ()?>

Inside a class definition, you can create a new object with both new self and new parent.
When assigning an instance of an object that has already been created to a new variable, the new variable accesses the same instance and assigns a value to that object. This behavior is the same as when the function is passed into the instance. You can use clones to create a new instance of an object that has already been created.
Example #4 Object Assignment

Include_once (' class1.php '); $instance = new Simpleclass (); $assigned = $instance; $reference = & $instance; $instance- > var = ' $assigned would has this value '; $instance = null; $instance and $reference into Nullvar_dump ($instance), Var_dump ($reference), Var_dump ($assigned);

The output is:

Null
Null
Object (Simpleclass) #1 (1) {["var"]=> string "$assigned would have the This value"}

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

C

Lass test{    static public Function getnew ()    {        return new static;    }} Class Child extends test{} $obj 1 = new Test (), $obj 2 = new $obj 1;var_dump ($obj 1!== $obj 2); $obj 3 = Test::getnew (); Var_dump ($ Obj3 instanceof Test); $obj 4 = Child::getnew (); Var_dump ($obj 4 instanceof Child);

Output Result:

BOOL (TRUE)
BOOL (TRUE)
BOOL (TRUE)

3.extends

A class can inherit the methods and properties of another class in a declaration using the extends keyword. PHP does not support multiple inheritance, and a class can inherit only one base class (just as Java is single-inheritance).
Inherited methods and properties can be overwritten by re-declaring them with the same name. However, if the parent class defines a method with final, the method cannot be overwritten. The overridden method or property can be accessed through the parent::.
When overriding a method, the parameters must be consistent or PHP will issue an E_STRICT level error message. However, with the exception of constructors, constructors can use different parameters when overridden.
Example #6 Simple class Inheritance:

Class Extendclass extends simpleclass{    //Overriding the parent class method    function Displayvar ()    {        echo "extending CLASS<BR > ";        Parent::d Isplayvar ();    }} $extended = new Extendclass (), $extended-Displayvar ();

Output Result:

Extending class
1

4.::class

Since PHP 5.5, keyword class can also be used to parse the class name. With Classname::class you can get a string that contains the fully qualified name of the class ClassName. This is especially useful for classes that use namespaces.
Parsing of Example #7 class names

Namespace ns{    class classname{}    echo classname::class;}

Output Result:

Ns\classname

  • 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.