Home Backend Development PHP Tutorial Detailed explanation of properties in Yii

Detailed explanation of properties in Yii

Dec 29, 2017 pm 07:04 PM
property Attributes Detailed explanation

This article mainly introduces the properties (Property) in PHP's Yii framework, and explains in detail the steps to implement properties. Friends in need can refer to it. I hope to be helpful.

In PHP, the member variables of a class are also called properties. They are part of the class definition and are used to represent the state of an instance (that is, to distinguish between different instances of the class). In specific practice, we often want to use a slightly special method to read and write attributes. For example, if you need to perform trim operation on the label attribute every time, you can use the following code to achieve it:

$object->label = trim($label);
Copy after login

The disadvantage of the above code is that as long as the label attribute is modified, the trim() function must be called again. If you need to handle the label attribute in other ways in the future, such as capitalizing the first letter, you will have to modify all the code that assigns values ​​to the label attribute. This duplication of code can lead to bugs, and this practice obviously needs to be avoided whenever possible.

To solve this problem, Yii introduces a base class named yii\base\Object, which supports defining properties based on the getter and setter (reader and setter) methods within the class. If a class needs to support this feature, it only needs to inherit yii\base\Object or its subclasses.

Supplement: Almost every core class of the Yii framework inherits from yii\base\Object or its subclasses. This means that whenever you see a getter or setter method in a core class, you can call it just like a property.
The getter method is a method whose name starts with get, while the setter method name starts with set. The part after get or set in the method name defines the name of the property. As shown in the following code, the getter method getLabel() and the setter method setLabel() operate on the label attribute:

namespace app\components;

use yii\base\Object;

class Foo extend Object
{
  private $_label;

  public function getLabel()
  {
    return $this->_label;
  }

  public function setLabel($value)
  {
    $this->_label = trim($value);
  }
}
Copy after login

(Detailed explanation: The getter and setter methods create an attribute named label. In this In the example, it points to a private internal property _label.)

The properties defined by getter/setter are used in the same way as class member variables. The main difference between the two is that when this property is read, the corresponding getter method will be called; and when the property is assigned a value, the corresponding setter method will be called. For example:

// 等效于 $label = $object->getLabel();
$label = $object->label;

// 等效于 $object->setLabel('abc');
$object->label = 'abc';
Copy after login

A property that only defines a getter and no setter is a read-only property. Attempting to assign to such a property will result in a yii\base\InvalidCallException (invalid call) exception. Similarly, properties defined with only setter methods but no getter methods are write-only properties, and attempts to read such properties will also trigger an exception. There are almost no cases for using write-only properties.

Properties defined through getters and setters also have some special rules and restrictions:

The names of such properties are not case-sensitive. For example, $object->label and $object->Label are the same property. Because PHP method names are not case-sensitive.
If the name of this type of attribute is the same as the class member variable, the latter shall prevail. For example, suppose the above Foo class has a label member variable, and then assigning a value to $object->label = 'abc' will be assigned to the member variable instead of the setter setLabel() method.
This type of attribute does not support visibility (access restrictions). Whether a property's getter and setter methods are public, protected, or private has no effect on the property's visibility.
The getter and setter methods of this type of property can only be defined as non-static. If they are defined as static methods (static), they will not be processed in the same way.
Going back to the problem mentioned at the beginning, instead of calling the trim() function everywhere, now we only need to call it once within the setter setLabel() method. If a new requirement comes that the first letter of the label becomes capitalized, we only need to modify the setLabel() method without touching any other code.

Steps to implement attributes

We know that when reading and writing a non-existent member variable of an object, __get() __set() will be automatically transfer. Yii takes advantage of this to provide support for attributes. From the above code, you can see that if you access a certain property of an object, Yii will call the function named getpropertyname(). For example, SomeObject->Foo will automatically call SomeObject->getFoo(). If a property is modified, the corresponding setter function will be called. For example, SomeObject->Foo = $someValue will automatically call SomeObject->setFoo($someValue).

Therefore, to implement properties, there are usually three steps:

  • Inherited from yii\base\Object.

  • Declare a private member variable used to save this property.

  • Provide getter or setter functions, or both, for accessing and modifying the private member variables mentioned above. If only the getter is provided, the property is read-only, and if only the setter is provided, the property is write-only.

The following Post class implements the readable and writable attribute title:

class Post extends yii\base\Object  // 第一步:继承自 yii\base\Object
{
  private $_title;         // 第二步:声明一个私有成员变量

  public function getTitle()    // 第三步:提供getter和setter
  {
    return $this->_title;
  }

  public function setTitle($value)
  {
    $this->_title = trim($value);
  }
}
Copy after login

Theoretically, it is also possible to write private $_title as public $title. Implements reading and writing of $post->title. But this is not a good habit for the following reasons:

Lost the encapsulation of the class. Generally speaking, it is a good programming practice to make member variables invisible to the outside world. You may not see it from here, but if one day you don’t want users to modify the title, how do you change it? How to ensure that the title is not modified directly in the code? If a setter is provided, as long as the setter is deleted, an exception will be thrown if there are uncleaned writes to the header. If you use the public $title method, you can check writing exceptions by changing it to private $title, but reading is also prohibited.
For title writing, you want to remove spaces. Using the setter method, you only need to call trim() at this place like the above code snippet. But if you use the public $title method, then there is no doubt that trim() will be called on every write statement. Can you guarantee that nothing is missing?
Therefore, using public $title is only quick and seems simple, but future modifications will be troublesome. It can be said to be a nightmare. This is the meaning of software engineering, making the code easy to maintain and modify through certain methods. It may seem unnecessary at first, but in fact, friends who have suffered losses or were forced by the client's boss to modify the code written by the previous programmer and greeted his relatives will all feel that this is very necessary.

However, there are no absolutes in this world. Since __get() and __set() are traversed through all member variables, they are called only when no matching member variable is found. Therefore, its efficiency is inherently lower than using member variables. In some simple situations where data structures, data collections, etc. are represented, and read-write control is not required, you can consider using member variables as attributes, which can improve efficiency.

Another little trick to improve efficiency is: use $pro = $object->getPro() instead of $pro = $object->pro, use $objcect->setPro($value) instead of $object->pro = $value. This has the same functional effect, but avoids the use of __get() and __set(), which is equivalent to bypassing the traversal process.

Maybe someone should scold me here. Yii finally implemented the attribute mechanism just to facilitate developers. However, I am here to teach you how to use the original method to improve the so-called efficiency. Well, indeed, there is a certain contradiction between convenience of development and high efficiency of execution. My personal point of view is more inclined to put convenience first, and make good use of the convenient conditions Yii creates for us. As for efficiency, the framework itself needs to pay more attention to it. As long as we don't write any extra code, it will be fine.

But you can rest assured that in the Yii framework, code like $app->request rarely appears, instead $app->getRequest() is used. In other words, the framework itself pays special attention to efficiency, and convenience is left to developers. In short, here is just a point of knowledge. As for whether to use it and how to use it, it is completely up to you.

It is worth noting:

The timing of automatically calling __get() __set() only occurs when accessing non-existent member variables. Therefore, if the member variable public $title is defined, then even if getTitle() setTitle() is defined, they will not be called. Because $post->title will directly point to the pulic $title, __get() __set() will not be called. It was severed from the root.
Since PHP is not case-sensitive for class methods, that is, $post->getTitle() and $post->gettitle() call the same function. Therefore, $post->title and $post->Title are the same property. That is, attribute names are also case-insensitive.
Since __get() __set() are both public, it makes no sense whether getTitle() setTitle() is declared as public, private, or protected. It is also accessible from the outside. Therefore, all properties are public.
Since neither __get() __set() is static, there is no way to use static attributes.
Other property-related methods of Object

In addition to __get() __set(), yii\base\Object also provides the following methods to facilitate the use of properties:

  • __isset() is used to test whether the property value is not null, and is automatically called when isset($object->property). Note that this property must have a corresponding getter.

  • #__unset() is used to set the property value to null and is automatically called when unset($object->property). Note that this property must have a corresponding setter.

  • hasProperty() is used to test whether there is a certain property. That is, a getter or setter is defined. If the parameter $checkVars = true of hasProperty() (the default is true), then any member variable with the same name is also considered to have this property, such as the public $title mentioned earlier.

  • canGetProperty() tests whether a property is readable. The meaning of the parameter $checkVars is the same as above. As long as the getter is defined, the property is readable. Also, if $checkVars is true . Then as long as the class defines member variables, whether they are public, private or protected, they are considered readable.

  • canSetProperty() tests whether a property is writable. The meaning of the parameter $checkVars is the same as above. As long as the setter is defined, the property can be written. At the same time, $checkVars is true . Then as long as the class defines member variables, whether they are public, private or protected, they are considered writable.

  • Object and Component

yii\base\Component inherits from yii\base\Object, therefore, it also has basic functions such as properties.

However, since Component also introduces events and behaviors, it does not simply inherit the property implementation method of Object, but overloads functions such as __get() __set() based on the same mechanism. But in terms of implementation mechanism, they are the same. This does not affect understanding.

As mentioned before, Yii is officially positioned as a component-based framework. The concept of visible components is the foundation of Yii. If you are interested in reading the source code or API documentation of Yii, you will find that almost all core classes of Yii are derived from (inherited from) yii\base\Component.

In Yii1.1, there was already a component, which was CComponent at that time. Yii2 splits the CComponent in Yii1.1 into two classes: yii\base\Object and yii\base\Component.

Among them, Object is relatively lightweight and defines the properties of the class through getters and setters. Component is derived from Object and supports events and behaviors. Therefore, the Component class has three important characteristics:

  • Property

  • Event

  • Behavior

I believe you have more or less understood that these three features are important entry points for enriching and expanding class functions and changing class behaviors. Therefore, Component has a very high status in Yii.

While providing more functions and convenience, Component has added the two features of event and behavior, which facilitates development while sacrificing a certain amount of efficiency. If you do not need to use the two features of event and behavior during development, such as a class that represents some data. Then, you can inherit from Object instead of Component. A typical application scenario is to use Object if it represents a set of data input by the user. And if you need to handle the behavior of the object and the events that can respond to the processing, there is no doubt that Component should be used. In terms of efficiency, Object is closer to the native PHP class, so when possible, Object should be used first.

Related recommendations:

Detailed explanation of Yii operating mechanism and routing

# #YiiHow to hide index.php in the URL

PHP Yii framework database query operation summary

The above is the detailed content of Detailed explanation of properties in Yii. 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)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

bottom attribute syntax in CSS bottom attribute syntax in CSS Feb 21, 2024 pm 03:30 PM

Bottom attribute syntax and code examples in CSS In CSS, the bottom attribute is used to specify the distance between an element and the bottom of the container. It controls the position of an element relative to the bottom of its parent element. The syntax of the bottom attribute is as follows: element{bottom:value;} where element represents the element to which the style is to be applied, and value represents the bottom value to be set. value can be a specific length value, such as pixels

Detailed analysis of C language learning route Detailed analysis of C language learning route Feb 18, 2024 am 10:38 AM

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,

See all articles