Table of Contents
(1), 3 ways of data access
(2) Specific code
Home Backend Development PHP Tutorial Detailed explanation of the three data access methods of PHP object-oriented (code examples)

Detailed explanation of the three data access methods of PHP object-oriented (code examples)

May 24, 2020 pm 05:15 PM
object-oriented

Objective of this article

Master the definition and function of the three methods of data access in PHP

1, public

2, protected

3, private

(1), 3 ways of data access

1,Public: Public class members

can be accessed anywhere, specifically which ones can be accessed:

● The class that defines the class (self)

● Subclasses of this class

● Other classes

2, Protected: Protected class members

● The class that defines this class ( Self)

● Subclasses of this class

3, Private: Private class members

● Only self can access

Summary: From top to bottom, the ability to constrain is getting stronger and stronger

It is still a bit difficult for us to understand simply from the above text description, so we should still follow the theoretical and practical approach To understand, then we will use specific codes to understand how these three data access methods are implemented in PHP, what are their respective characteristics, and finally, let’s understand their binding capabilities. how.

(2) Specific code

Description: In order to allow everyone to better understand object-oriented, when writing articles, I also try to follow certain rules. From shallow to deep, from easy to difficult, so every article I write is related to the previous article. For example, in the following code case, I expand and extend the code of the previous article.

Case 1: Know the definition of public, and then prove that it can be accessed in 3 places (1. In a class defined by yourself, 2. In subclass 3. Outside)

<?php

//定义 “人” 类
class Human{
    public $name = "";//姓名 
    public $height = "";//身高
    public $weight = "";//体重

    public function eat($food){
        echo $this->name."在吃".$food."<br/>";
    }
}
//女主播
class Anchors extends Human{
    public $name = "";
    public $stageName = "";
    public function __construct( $name,$stageName ){
        $this->name = $name;
        $this->stageName = $stageName;
    }
    public function singing(){
        echo "我是女主播,我会唱歌<br/>";
    }
  
}
// Nba球员类
 class NbaPlayer extends Human{
   //因为父类已经有了,所以就不需要再写了,通过extends来实现
    // public $name  = "";//姓名
    // public $height = "";//身高
    // public $weight = "";//体重

    public $team = "";//团队
    public $playerName = "";//球员号码

    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    
   
   //跑步
    public function run(){
        echo "跑步中<br/>";
    }
    //跳跃
    public function jump(){
        echo "跳跃<br/>";
    }
    //运球
    public function dribble(){
        echo "运球<br/>";
    } 
    //传球
    public function pass(){
        echo "传球<br/>";
    }
    //投篮
    public function shoot(){
        echo "投篮<br/>";
    }
    //扣篮
    public function dunk(){
        echo "扣篮<br/>";
    }
 }

 //数据访问测试
//public 测试
//1、测试在类的外部可以访问
 //创建乔丹对象
 $jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");
 //输出乔丹对象
 echo "名称= ".$jordon->name."<br/>";//结果能够输出来,说明在外部是可以访问Public类成员的

//2、测试在类的自身里面可以访问
//例子:比如构造函数里,我们可以直接通过$this->team

//3、测试是否可以子类中可以访问
//例子:比如父类中定义的name 一样可以在子类(NbaPlayer)的构造函数中直接访问

?>
Copy after login

The running effect is as follows:

Detailed explanation of the three data access methods of PHP object-oriented (code examples)

Case Two: Know the definition of protected, and then prove that it can be accessed in two places (1. In the class defined by yourself, 2. In the subclass)

<?php
//定义“人”类
class Human{
    public $name = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重

    protected $addr = "长沙";//受保护的类
   
    public function eat($food){
        echo $this->name."在吃".$food."<br/>";
    }
    //测试protected类成员是否可以在自身类中可以访问
    public function getAddrInHuman(){
        echo "Human 自身类中的add=".$this->addr."<br/>";
    }
}
//女主播
class Anchors extends Human{
    public $name = "";
    public $stageName = "";
    public function __construct( $name,$stageName ){
        $this->name = $name;
        $this->stageName = $stageName;
    }
    public function singing(){
        echo "我是女主播,我会唱歌<br/>";
    }
    //重写方法eat
    public function  eat($food){
        echo "我是女主播,我是边唱歌边吃{$food}<br/>";
    }
}
 class NbaPlayer extends Human{
   //因为父类已经有了,所以就不需要再写了,通过extends来实现
    // public $name  = "";//姓名
    // public $height = "";//身高
    // public $weight = "";//体重

    public $team = "";//团队
    public $playerName = "";//球员号码

    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    
    //测试protected类成员是否可以在子类中可以访问
    public function getAddrInNbaPlayer(){
        echo "在NbaPlayer子类中addr=".$this->addr."<br/>";
    }
 }

 //创建乔丹对象
 $jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");

 //数据访问测试
 //protected测试
 //1、测试是否可以在自身类中可以访问
 $jordon->getAddrInHuman();//结果OK,确实是可以访问
 //2.测试是否可以在子类中访问
 $jordon->getAddrInNbaPlayer();//结果OK,确实也是可以访问
 //3.测试是否可以被外部访问
 echo "在类外部访问addr=".$jordon->addr."<br/>";//结果报错,说明不行

?>
Copy after login

The operation effect is as follows:

Detailed explanation of the three data access methods of PHP object-oriented (code examples)


Case 3: Know the definition of private, and then prove that it can only be used in 1 place Access (1. In a self-defined class)

<?php
//定义“人”类
class Human{
    public $name = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重

    private $isHungry = true;//测试私有变量是否可以在子类中访问
  
    //为了让外部可以访问private类成员
    public function getPrivateInfo(){
        return "private 变量 isHungry=".$this->isHungry."<br/>";
    }
}
//女主播
class Anchors extends Human{
    public $name = "";
    public $stageName = "";
    public function __construct( $name,$stageName ){
        $this->name = $name;
        $this->stageName = $stageName;
    }
    public function singing(){
        echo "我是女主播,我会唱歌<br/>";
    }
    //重写方法eat
    public function  eat($food){
        echo "我是女主播,我是边唱歌边吃{$food}<br/>";
    }
}
 class NbaPlayer extends Human{
   //因为父类已经有了,所以就不需要再写了,通过extends来实现
    // public $name  = "";//姓名
    // public $height = "";//身高
    // public $weight = "";//体重

    public $team = "";//团队
    public $playerName = "";//球员号码

    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        // echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    //测试private类成员是否可以在子类中访问
    public function getIsHungryInNbaPlayer(){
        echo "在NbaPlayer子类中isHungry=".$this->isHungry."<br/>";
    }
 }
 
 //创建乔丹对象
 $jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");

 //数据访问测试
 //private测试
 //1.测试私有变量能否被外部访问
 echo "私有变量isHungry =".$jordon->isHungry ."<br/>";//结果不能访问,说明private变量不能被子类访问
 //测试私有变量能否在定义的类的内部访问
 echo $jordon->getPrivateInfo();//结果Ok,说明可以 
//测试私有变量是否可以在子类中访问
$jordon->getIsHungryInNbaPlayer();//结果报错,说明也不能在子类中访问

?>
Copy after login

The operation effect is as follows:

Detailed explanation of the three data access methods of PHP object-oriented (code examples)

Summary:

1. Public: Public class members

can be accessed anywhere, specifically which ones can be accessed:

● The class that defines the class (self)

● Subclasses of this class

● Other classes

2. Protected: Protected class members

● Can be accessed by itself and its subclasses

3. Private: Private class members

● Only you can access them

4. In order to allow the outside world to access private class members, we can define a public class member in the class method, and then return the private class member in the public method

Okay, now that we are here, I think everyone should have a clearer understanding of data access, so let’s apply what we have learned now. Knowledge to solve the following questions, first think about how to do it, and then look at the answer

Question: NBA players generally don’t want others to know their real names. For example, I am obviously 40 years old, but I I just want others to think I am 38 years old

Thinking......................

The answer is revealed :

The code is as follows:

<?php

class Human{
    public $name = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重

}
//女主播
class Anchors extends Human{
    public $name = "";
    public $stageName = "";
    public function __construct( $name,$stageName ){
        $this->name = $name;
        $this->stageName = $stageName;
    }
    public function singing(){
        echo "我是女主播,我会唱歌<br/>";
    }
    //重写方法eat
    public function  eat($food){
        echo "我是女主播,我是边唱歌边吃{$food}<br/>";
    }
}
 class NbaPlayer extends Human{
   //因为父类已经有了,所以就不需要再写了,通过extends来实现
    // public $name  = "";//姓名
    // public $height = "";//身高
    // public $weight = "";//体重

    public $team = "";//团队
    public $playerName = "";//球员号码

     //数据访问
     private $age = "40";
     //end

    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    
   
   //跑步
    public function run(){
        echo "跑步中<br/>";
    }
    //跳跃
    public function jump(){
        echo "跳跃<br/>";
    }
    //运球
    public function dribble(){
        echo "运球<br/>";
    } 
    //传球
    public function pass(){
        echo "传球<br/>";
    }
    //投篮
    public function shoot(){
        echo "投篮<br/>";
    }
    //扣篮
    public function dunk(){
        echo "扣篮<br/>";
    }
  
    //数据访问 
    public function getAge(){
        // echo $this->name."的age=".$this->age."<br/>";
        //既然能够在自身类中获取到年龄,那么为了解决NBA球员不想让别人知道自己真实年龄的问题
            //我们就可以对年龄进行操作-造假 让年龄更小
        $age = $this->age-2;
        echo $this->name."的age=".$age."<br/>";
    }
 }
 
 //创建乔丹对象
 $jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");
 $jordon->getAge();//结果Ok 说明年龄是可以获取到的,既然可以获取到age我们在函数内部作假,来达到一个谎报年龄的目的
?>
Copy after login

The running effect is as follows:

Detailed explanation of the three data access methods of PHP object-oriented (code examples)

##Summary:

1. Know that there are three forms of data access in PHP, public, protected, private

2. Know the characteristics of the three data access methods

The above is the detailed content of Detailed explanation of the three data access methods of PHP object-oriented (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement object-oriented event-driven programming using Go language How to implement object-oriented event-driven programming using Go language Jul 20, 2023 pm 10:36 PM

How to use Go language to implement object-oriented event-driven programming Introduction: The object-oriented programming paradigm is widely used in software development, and event-driven programming is a common programming model that realizes the program flow through the triggering and processing of events. control. This article will introduce how to implement object-oriented event-driven programming using Go language and provide code examples. 1. The concept of event-driven programming Event-driven programming is a programming model based on events and messages, which transfers the flow control of the program to the triggering and processing of events. in event driven

What is the importance of @JsonIdentityInfo annotation using Jackson in Java? What is the importance of @JsonIdentityInfo annotation using Jackson in Java? Sep 23, 2023 am 09:37 AM

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate object identity during serialization and deserialization. ObjectIdGenerators.PropertyGenerator is an abstract placeholder class used to represent situations where the object identifier to be used comes from a POJO property. Syntax@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})@Retention(value=RUNTIME)public

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Aug 14, 2023 pm 05:25 PM

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming In object-oriented programming, design pattern is a commonly used software design method, which can improve the readability, maintainability and scalability of the code. Flyweight pattern is one of the design patterns that reduces memory overhead by sharing objects. This article will explore how to use flyweight mode in PHP to improve program performance. What is flyweight mode? Flyweight pattern is a structural design pattern whose purpose is to share the same object between different objects.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming Jun 05, 2024 pm 08:50 PM

By mastering tracking object status, setting breakpoints, tracking exceptions and utilizing the xdebug extension, you can effectively debug PHP object-oriented programming code. 1. Track object status: Use var_dump() and print_r() to view object attributes and method values. 2. Set a breakpoint: Set a breakpoint in the development environment, and the debugger will pause when execution reaches the breakpoint, making it easier to check the object status. 3. Trace exceptions: Use try-catch blocks and getTraceAsString() to get the stack trace and message when the exception occurs. 4. Use the debugger: The xdebug_var_dump() function can inspect the contents of variables during code execution.

See all articles