PHP Object-Oriented encapsulation

Source: Internet
Author: User

<?php
The concept of a class
The concept of objects
Defining classes
Class Ren
{
Member variables
Member Methods
}
Created objects
$r =new Ren ();
Call the member of the object $r->

Object-oriented three main features: encapsulation, inheritance, polymorphism
1. Encapsulation
Purpose: Make classes more secure: Do not let outsiders directly access the members of the class

Specific practices:
1. member becomes private: access modifier: (Public private privately owned protected protected, only that class and subclass are accessible)
2. Create a member method to manipulate variables

Class Ren
{

private $age;//Privacy Member
Private $name;
Private $sex;
Constructor initializes the member variables when the object is created.
/* Special point: 1. Special execution time: Automatic execution when object new is created
2. Special __construct * *
function __construct ($s)
{
$this->sex= $s;
}

/* (Method one)
Methods to assign values to variables
Public function setage ($a)
{
if ($a >18and$a<50)
{
$this->age= $a;
}
}
Take value
function Getage ()
{
return $this->age;
}*/

(Method Two)
3. The __get () and __set () methods provided in the applicable class, the method of assigning values to variables
function __set ($n, $v)
{
if ($n = = "Age")
{
if ($v >18and $v <50)
{
$this $n = $v;
}
}
Else
{
$this $n = $v;
}
}
Method of taking value
function __get ($n)
{
return $this $n;
}
}

$r =new Ren ("male");
$r->age=20;
$r->name= "Zhang San";
Echo $r->name;
Var_dump ($R);


?>

PHP Object-Oriented encapsulation

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.