PHP 13: Class

Source: Internet
Author: User
Notice:this article is working on progress!

This chapter introduces the PHP classes.
Now, basically every language supports object-oriented, and of course PHP is not listed.
PHP does not support object-oriented in previous versions, but has been supported since PHP4, including PHP4. This series will take PHP5 as an example to describe object-oriented knowledge. The knowledge of PHP4 will also be mentioned later.
The ability of PHP to support object-oriented, in my personal view, no C++,c#,java and other languages so deep, even so, it is more comprehensive.
You ask what is the object-oriented character of each person now? They certainly answer encapsulation, polymorphism, inheritance, yes, that's all.

Class
Well, let's start with the class. The concept of class is not said, and the world knows it.
The classes in PHP can be written like this:

Class Page
{

}
?>

It defines a simple class page with nothing at all.
You can also define properties and methods, as follows:

Class Page
{
2 attributes
var $attribute 1;
var $attribute 2;

2 functions
function Operation1 ()
{
}

function Operation2 ($param 1, $param 2)
{
}
}
?>

Does the PHP class have a constructor and destructor? The answer is yes, there is! So is it the same as C + +? No, it has a special function.
Construction with __construct (); __destruct (); (Note: Front is 2 underscores)
The code is as follows:

1 2 class Page
3 {
4//2 attributes
5 var $attribute 1;
6 var $attribute 2;
7
8//2 functions
9 function Operation1 ()
10 {
11}
12
function Operation2 ($param 1, $param 2)
14 {
15}
16
+//Construction function
function __construct ($param)
19 {
$this-attribute1 = $param;
21}
22
//Destruction function
function __destruct ()
25 {
attribute1-$this = 0;
27}
28}
?>

Does PHP support overloading? Yes, PHP supports overloading, so it can be constructed in a number of ways.
Instantiation of a class
Building a class, we need to apply it, how to use it? Instantiate, this is the same as in other languages, so just give the code:

1 2 class Page
3 {
4//2 attributes
5 var $attribute 1;
6 var $attribute 2;
7
8//2 functions
9 function Operation1 ()
10 {
11}
12
function Operation2 ($param 1, $param 2)
14 {
15}
16
+//Construction function
function __construct ($param)
19 {
$this-attribute1 = $param;
echo "It'll construct the attribute: {$this->attribute1}
" ;
22}
23
//Destruction function
function __destruct ()
26 {
attribute1-$this = 0;
28}
29}
$instance 1 = new page ("Attribute1 in Instance 1");
$instance 2 = new page ("Attribute2 in Instance 2");
$instance 1 = new Page ();
?>

The output is:

1 It'll construct the attribute:attribute1 in instance 1
2 It'll construct the Attribute:attribute2 in instance 2
3 It'll construct the attribute:


Set or Get Properties
This question is very interesting.
For the example above, $attribute 1 is an attribute, and we can use $this-attribute1 to get or set its value.
But in order to better reflect the encapsulation of the class, or the use of PHP provided by the Get or set method, this and C # function in this way. However, in PHP, there are 2 methods: __get ($name), __set ($name, $value) function to set properties.
Another benefit of doing this is to add your own logic according to the actual needs, if the direct assignment is not possible. For example, if the attribute must be a number between 1-100, what should I do? Or the use of __set bar. Let's look at the code:


1 2 class Page
3 {
4//2 Attributes
5 var $attribute 1;
6 var $attribute 2;
7
8//2 functions
9 function Operation1 ()
10 {
11}
12
function Operation2 ($param 1, $param 2)
14 {
15}
16
//construction function
function __construct ($param)
19 {
$this->attribute1= $param;
echo "It'll construct the attribute: {$this->attribute1}
";
22}
23
//destruction function
function __destruct ()
26 {
->attribute1=0; $this
28}
function __set ($name, $value)
30 {
if ($name = = = "Attribute2" && $value >=2&&attribute2<=100)
32 {
$this->attribute2= $value;
34}
35}
function __get ($name)
37 {
$name $this,
39}
40}
$instance 1=new page ("Attribute1 in Instance 1");
$instance 2=new page ("Attribute1 in Instance 1");
$instance 3=new Page ();
$instance 3->attribute2=99;
Echo $instance 3->attribute2;
?>


Visibility of class members and methods
It's public,private and protected. The same as C #. However, it is important to note that PHP defaults to public, not the default private for most languages. Based on this, the above example can be used. It is also important to note that if you use these 3 keywords, var is omitted. Let's see an example.


1 2 class Page
3 {
4//2 Attributes
5 public $attribute 1;
6 Public $attribute 2;
7
8//2 functions
9 Public Function Operation1 ()
10 {
11}
12
Public Function Operation2 ($param 1, $param 2)
14 {
15}
16
//construction function
Public function __construct ($param)
19 {
$this->attribute1= $param;
echo "It'll construct the attribute: {$this->attribute1}
";
22}
23
//destruction function
Public Function __destruct ()
26 {
->attribute1=0; $this
28}
Public Function __set ($name, $value)
30 {
if ($name = = = "Attribute2" && $value >=2&&attribute2<=100)
32 {
$this->attribute2= $value;
34}
35}
Public Function __get ($name)
37 {
$name $this,
39}
40}
$instance 1=new page ("Attribute1 in Instance 1");
$instance 2=new page ("Attribute1 in Instance 1");
$instance 3=new Page ();
$instance 3->attribute2=99;
Echo $instance 3->attribute2;
?>


Inheritance of Classes
The inheritance of a class is like a C#,java language, and multiple inheritance is not supported. PHP utility extends to inherit a class, similar to Java.
In Java there is the word final, and PHP has a similar function, just to prevent inheritance or overloading, overriding the method.
Refer to inheritance, then PHP support interface? Support. For example:

1 2 Interface IDispose
3 {
4 function Dispose ();
5}
6
7 Class Page extends IDispose
8 {
9 function Dispose ()
10 {
One//Your code here.
12}
13}
?>

New advanced Features for PHP
1. Per-class Constants
It was introduced in the PHP5. This commonsense does not need to be initialized. For example:


1 2 class Math
3 {
4 const pi=3.1415927;
5}
6 echo "Math::p i=". Math::p I. " \ n ";
7?>

is actually the same as a static variable in C + +.
2. Static functions
Since we are talking about static variables, of course, static functions are also needed. It is the same as the idea above, the implementation of the need to add static keyword, a lot of languages are like this. C#,java and so on.
The code can be as follows:


1 2 class Shape
3 {
4 static function Squredsize ($length)
5 {
6 return $length * $LENGTH;
7}
8}
9 echo "Squre:". Shape::squredsize (10);
Ten?>

3. Type checking of classes in PHP
You want to decide whether a class is a class type or not. Very simple, that is instanceof, if you have used Java, then you are very familiar with, because the same as Java. If you are using C #, it is similar to the IS in C #.
4. Cloning objects
PHP provides a keyword, clone, which is the function. I see PHP as one of the simpler languages I've seen cloning objects in a language. The code is as follows:

$c = Clone $b

What if you want to change a feature of $c? This time you need to rewrite the __clone method.
5. Abstract class
PHP also supports abstract classes, and is very similar to languages such as C #. Let's give an example.


1!--? php
2 abstract class Shape
3 {
4 abstract protected function getsqu Ared ();
5 Abstract protected function getlinecount ();
6 Public Function Printshapevalue ()
7 {
8 echoes "The squared size is: {$this->getsquared ()}
";
9 echo "and the number of lines is: {$this->getlinecount ()}
";
Ten}
One}

class Rectange extends Shape
+ {
protected function getsquared ()
+ {
12*12 return;

Protected function Getlinecount ()
{
4;

+}

Class Triangle extends Shape
+ {
protected function getsquared ()
+ {
return 10*12;
3}
to protected function Getlinecount ()
+
(+)------
=new}


PNs $rect rectange ();
$rect->printshapevalue ();
=new
$tri Triangle ();
$tri->printshapevalue ();
?>

The results of the output are as follows:

The squared size is:144
and the number of lines is:4
The squared size is:120
and the number of lines Is:3

Notice how the abstract function is written, as an abstract keyword. And in subclasses, there is no override keyword, but a direct rewrite. This is different from C #.
6. Using the __call overload
This is what I think PHP provides a very cool feature, very admire. This method is used to monitor other methods in an object. If you try to invoke a method that does not exist in an object, the __call method will be called automatically.
Let me give you an example. The code is as follows:


1 2 class Caller
3 {
4 Private $x = Array (1, 2, 3);
5
6 Public Function __call ($m, $a)
7 {
8 print "Method $m called:\n";
9 var_dump ($a);
Ten return $this->x;
11}
12}
13
$foo = new Caller ();
$a = $foo->test1 (1, "2", 3.4, true);
Var_dump ($a);
?>

The results shown are as follows:

Method test1 Called:array (4) {[0] = Int (1) [1] = string (1) "2" [2] = = Float (3.4) [3] =& Gt BOOL (TRUE)} array (3) {[0] = = Int (1) [1] + int (2) [2] = = Int (3)}

$foo->test1 This method does not exist in the Foo class, but after defining the __call, it is possible.
7. Use the __autoload () method.
This feature is still cool. Many developers write image-oriented applications to create a PHP source file for each class definition. A great pain is having to write a long list of included files at the beginning of each script (one file per class). In PHP 5, we don't need this anymore. The __autoload function is easy to handle, and this method is called automatically when the Code view uses an undefined class. By calling this function, the scripting engine has the last chance to remediate the required classes before the error fails. However, it is important to note that the exception thrown by the __autoload function cannot be caught by a catch statement block and causes a fatal error.
An example:

1 2 function __autoload ($class _name) {
3 require_once $class _name. '. php ';
4}
5
6 $obj 1 = new MyClass1 ();
7 $obj 2 = new MyClass2 ();
8?>

8, implement iteration or iteration.
It iterates through all the visible attributes of the class, as well as the values, etc.
9. Converts the type to a string (__tostring ()).
This is the application of a magic function, __tostring (). It's a bit like the toString () function in C #, but it's different for the class itself. If you implement this function in a PHP class, they will call this function when they print the class, for example:

1 2 class Page
3 {
4 Public Function __tostring ()
5 {
6 return ' Hello ';
7}
8}
9 $page = new page ();
Echo $page;
?>

It will output:

Hello

10. Reflections.
I didn't expect PHP to support reflection. If you're familiar with C # reflection, I don't have to say it. If not, please keep looking down.
Reflection is the ability to find information about what it contains through a class or object. When the document information of this class is unknown or not provided, some properties, methods, etc. of the class can be obtained by reflection.
Reflection inherits some of the classes of Zend. For practical use, see the documentation for the class that is reflected in PHP.
  • 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.