Php object-oriented BASICS (2) and php object-oriented Basics

Source: Internet
Author: User

Php object-oriented BASICS (2) and php object-oriented Basics

Three features of object-oriented
1. Encapsulation
Objective: To make the class more secure
Practice:
A. Change member variables to private
B. Make a member Method for indirect access
C. add restrictions to this method.
Class Ren
{
Private $ age; // between 18 and 50
Private $ name;
// Magic method, assign a value to the variable
Function _ set ($ n, $ v)
{
If ($ n = "age ")
{
If ($ n >=18 & $ n <= 50)
{
$ This-> $ n = $ v;
}
}
Else
{
$ This-> $ n = $ v;
}
}
// Magic mode, variable value
Function _ get ($ n)
{
Return $ this-> $ n;
}
// The following method applies only to one or two variables:
/* Function setAge ($ n)
{
If ($ n >=18 & $ n <= 50)
{
$ This-> age = $ n;
}
}
Function getAge ()
{
Return $ this-> age;
}*/
}
$ R = new Ren ();
$ R->__ set ("age", 20 );
$ R-> age = 20;
$ R-> name = "James ";
Var_dump ($ r );

2. Inheritance
Subclass can inherit everything from the parent class (except for Private Members)
Features: single inheritance
Class Ren
{
Private $ name;
Function Run ()
{
Echo "running: <br> ";
}
}
Class China extends Ren // who inherits extends
{
// Override
Function Run ()
{
Parent: Run ();
Echo "Chinese running ";
}
}
$ C = new China ();
$ C-> Run ();
Var_dump ($ c );

3. Polymorphism(Weak languages cannot implement polymorphism)
Definition: when a parent class references a subclass instance, the method of the parent class is overwritten by the subclass.

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.