search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the three data access methods of PHP object-oriented (code examples)

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)的构造函数中直接访问

?>

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/>";//结果报错,说明不行

?>

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();//结果报错,说明也不能在子类中访问

?>

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我们在函数内部作假,来达到一个谎报年龄的目的
?>

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
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool