search
HomeheadlinesPHP Chinese website shows you PHP construction methods and access control

* Construction method and access control (querier and setter)

* Construction method:

* 1. Fixed method name: __constructor()

* 2 .Function: Declare operations that need to be completed automatically when creating an object, such as initializing object properties, or automatically calling methods in a class

* 3. A standardized class must have and can only have one constructor method

* Supplement: Methods starting with double underscores are called magic methods. Compared with ordinary methods:

* 1. Different callers: directly called by the object, the user does not have permission

* 2. Different calling scenarios: it can only be called in specific scenarios, and it is automatically called

* Common scenarios that trigger magic method calls are:

* 1. Object initialization ; 2. Query and setting of object attributes; 3. Object cloning; 4. Object serialization; 5. Object destruction; 6. Other scenarios...

* If a constructor is declared in the class, then the attributes There is no need to initialize when declaring

* You may be wondering, since initialization is no longer needed, why do you need to give $name an empty string, $age is 0, and $stature is an empty array?

* The reason is: PHP is a weakly typed language. Currently, arrays and objects already support type hints, but scalars, such as strings, and numerical types are still not supported.

* So give the attribute a representative value The initial value of the type can serve as a type hint. This is a good habit

*

* If the class attributes are initialized through the construction method in the class, it is no longer needed. Outside the class, the class attributes are initialized directly through assignment

* Therefore, there is no need for the attributes of the class to be obtained directly from the outside. For the sake of security and the need for data encapsulation, class attributes should not be allowed. External direct access

* Use the private keyword to modify the class attributes

* Private: can only be accessed within the method of this class, and cannot be accessed externally or by subclasses

* If the attributes in the class are private, then an access interface should be provided to the outside world

* This interface is implemented through class methods, and the access control is public, that is, it is accessible from outside the class

* Yes In the interface method, necessary detection is performed on external access to ensure that the request is legal and the data is safe and meaningful

* For external query (read) operations, set the query method to solve the problem

* The recommended query method name is: get attribute name, capitalize the first character of the attribute name, and use camel case naming method

* Queryers usually do not need to pass in parameters. If parameters are passed in, they are usually query conditions** *

class GirlFriend2 
{
    //类属性:$name 姓名
    public $name = '';
    private $name = '';
    //类属性: 年龄
    public $age = 0;
    private $age = 0;
    
    //类属性: 身材三维stature['stætʃə]: 胸,腰,臀
    public $stature = [];
    private $stature = [];
    //声明构造方法
    public function __construct($name,$age, array $stature) {
        //初始化类成员属性
        $this->name = $name;
        $this->age = $age;
        $this->stature = $stature;
    }
      //查询器: getName() 获取女友姓名
   public function getName()
   {   
       //返回当前对象的name属性值
       return $this->name;
   }
    
    // 通过查询器限制非法用户对类属性的访问
   public function getName($yourName='')
   {
       if (!empty($yourName) && $yourName != '西门大官人' ) {
           return $this->name;
       }
       return '非法访问';
   }
    
    //一个方法中,尽可能只用一个return,否则会警告return语句过多,建议做如下修改
    //添加一个临时变量,这样可确保方法内只会一个return语句
    public function getName($yourName='')
    {
        //创建方法内部变量(局部变量),用来保存要返回的信息
        $msg = '非法访问';
        if (!empty($yourName) && $yourName != '西门大官人' ) {
            $msg = $this->name;
        }
        return $msg;
    }
    
    //下面对年龄和三维的访问,你也可以通过对姓名的限制方式进行访问控制
    //查询器: getAge() 获取女友年龄
    public function getAge()
    {   
        //返回当前对象的age属性值
//        return $this->age;
        //下面是改写一下当前方法,加入一些逻辑判断,仅做演示,实际功能自己扩展
        $msg = $this->age;
        if ($msg >= 50) {
            $msg .= ', 口味够重呀,大兄弟~~';
        } elseif ($msg < 18) {
            $msg .= &#39;, 未成年呢,求放过~~&#39;;
        }        
        return $msg;
    }
    
    //查询器: getStature() 获取女友身材信息
    public function getStature()
    {
        //返回当前对象的$stature属性值
        return $this->stature;
    } 
    
    
    /**
     * 设置器:也叫修改器,允许外部修改类的属性值
     * 参数一般有二个: 属性名与新的属性值
     * 因为属性名在方法中已经指定,这里只需要传入一个新的属性值即可
     */
    //下面通过设置器来控制对类属性的修改操作
    public function setName($value=&#39;&#39;)
    {
        return $this->name = $value;
    }
    
    //设置器更多的应用场景是会属性值进行过滤检测,例如年龄的范围
    public function setAge($value)
    {
        //年龄必须在18~120之间
        if (in_array($value,range(14,120))){
            $this->age = $value;
        }
    }
}


Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.