Home Backend Development PHP Tutorial Detailed explanation of magic method __get() instance (php advanced object-oriented tutorial 2)

Detailed explanation of magic method __get() instance (php advanced object-oriented tutorial 2)

Apr 18, 2017 pm 06:02 PM

When you see this name, it gives you a very high-end feeling. Yes, magic methods are indeed advanced.

So, What is the magic method?

Methods starting with two underscores in PHP are called "Magic methods". For example, the __construct(), __destruct (), __clone() mentioned before, and __call(),,__get(), __set(),__sleep(), __wakeup(), __toString(), __autoload(), etc., They are all magic methods.

If you want PHP to call these magic methods, you must first define them in the class, otherwise PHP will not execute uncreated magic methods.

Note:

The magic method is set in PHP, so you cannot create it yourself. You can only use what already exists in PHP, otherwise an error will be reported.

Below we will introduce the commonly used magic methods among many magic methods.

__get() functions as:

__get(): When reading the value of an inaccessible attribute (private, protected, does not exist), php will execute __get() method.

Let’s take a look at an example about __get():

<?php
class Monkey{
public $name;
protected $food;
function __construct($name,$food){
$this->name = $name;
$this->food = $food;
}
function sayHello(){
echo &#39;<br/>我是&#39; . $this->name . &#39;我喜欢吃&#39; . $this->food;
}
}
$monkey = new Monkey(&#39;猴子&#39; , &#39;桃子&#39;)
$monkey -> sayHello();
Copy after login

The above example is the knowledge about classes we have talked about before, creating classes, creating methods, instantiating, and finally accessing .

Next we put forward a new requirement, that is, we need to call $food directly outside the class. Then some people will say that $food is a protected attribute and cannot be called directly. But the demand is to do this, what should we do? This is when our magic method __get() is used. Look at the following code:

<?php
class Monkey{
public $name;
protected $food;
function __construct($name,$food){
$this->name = $name;
$this->food = $food;
}
function sayHello(){
echo &#39;<br/>我是&#39; . $this->name . &#39;我喜欢吃&#39; . $this->food;
}
//魔术方法
function __get($pro_name){
//先判断$pro_name是否存在
if(isset($this -> $pro_name)){
return $this -> $pro_name;
}else{
echo &#39;属性值不存在&#39;;
}
}
}
$monkey = new Monkey(&#39;猴子&#39; , &#39;桃子&#39;)
$monkey -> sayHello();
echo &#39;猴子喜欢吃&#39; . $monkey -> food;
Copy after login

Before using the magic method, we need to first determine whether $pro_name exists. Because in the above example, $pro_name calls food, and food exists, so it can be called. But if food is replaced by something else that does not exist, such as a, then the __get() method will be called, but an error will be reported, saying that a does not exist. So we have to make a judgment first.

The above is the detailed content of Detailed explanation of magic method __get() instance (php advanced object-oriented tutorial 2). 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 automate tasks using PowerShell How to automate tasks using PowerShell Feb 20, 2024 pm 01:51 PM

If you are an IT administrator or technology expert, you must be aware of the importance of automation. Especially for Windows users, Microsoft PowerShell is one of the best automation tools. Microsoft offers a variety of tools for your automation needs, without the need to install third-party applications. This guide will detail how to leverage PowerShell to automate tasks. What is a PowerShell script? If you have experience using PowerShell, you may have used commands to configure your operating system. A script is a collection of these commands in a .ps1 file. .ps1 files contain scripts executed by PowerShell, such as basic Get-Help

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.

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

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.

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.

Example of Curl Get command Example of Curl Get command Mar 20, 2024 pm 06:56 PM

In Linux, URL or Curl client is a popular command line utility that allows you to transfer data over the network using various protocols such as HTTPS, HTTP, FTP, etc. It allows you to send and receive data using its get, post and request methods. Among them, you need to use the &quot;get&quot; method frequently. Therefore, it becomes crucial to learn various methods and various options that you can use to increase your productivity. &quot;Performing a curl operation is as simple as entering a few simple commands. Although it seems simple, many users do not fully realize its potential. Therefore, this short guide provides some information on how to perform curl operations on Linux systems. Example using the &quot;curlget&quot; command.&quot; Curl

See all articles