search
HomeBackend DevelopmentPHP TutorialProperty in PHP's Yii framework

Property in PHP's Yii framework

Nov 13, 2017 am 11:50 AM
phpyiiframe

Yii is a component-based, high-performance PHP framework for developing large-scale web applications. Yii is written in strict OOP and has complete library references and comprehensive tutorials. From MVC, DAO/ActiveRecord, widgets, caching, hierarchical RBAC, web services, to theming, I18N and L10N, Yii provides almost everything needed for today's Web 2.0 application development. In fact, Yii is one of the most efficient PHP frameworks.

Yii is a high-performance PHP5 web application development framework. A simple command line tool yiic can quickly create a web application code framework. Developers can add business logic based on the generated code framework to quickly complete application development.

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);

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);
  }
}

(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';

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 label should be 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 called. Yii takes advantage of this to provide support for attributes. From the above code, you can see that if you access a property of an object, Yii will call a function called 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);
  }
}

从理论上来讲,将 private $_title 写成 public $title ,也是可以实现对 $post->title 的读写的。但这不是好的习惯,理由如下:

失去了类的封装性。 一般而言,成员变量对外不可见是比较好的编程习惯。 从这里你也许没看出来,但是假如有一天,你不想让用户修改标题了,你怎么改? 怎么确保代码中没有直接修改标题? 如果提供了setter,只要把setter删掉,那么一旦有没清理干净的对标题的写入,就会抛出异常。 而使用 public $title 的方法的话,你改成 private $title 可以排查写入的异常,但是读取的也被禁止了。
对于标题的写入,你想去掉空格。 使用setter的方法,只需要像上面的代码段一样在这个地方调用 trim() 就可以了。 但如果使用 public $title 的方法,那么毫无疑问,每个写入语句都要调用 trim() 。 你能保证没有一处遗漏?
因此,使用 public $title 只是一时之快,看起来简单,但今后的修改是个麻烦事。 简直可以说是恶梦。这就是软件工程的意义所在,通过一定的方法,使代码易于维护、便于修改。 一时看着好像没必要,但实际上吃过亏的朋友或者被客户老板逼着修改上一个程序员写的代码,问候过他亲人的, 都会觉得这是十分必要的。

但是,世事无绝对。由于 __get() 和 __set() 是在遍历所有成员变量,找不到匹配的成员变量时才被调用。 因此,其效率天生地低于使用成员变量的形式。在一些表示数据结构、数据集合等简单情况下,且不需读写控制等, 可以考虑使用成员变量作为属性,这样可以提高一点效率。

另外一个提高效率的小技巧就是:使用 $pro = $object->getPro() 来代替 $pro = $object->pro , 用 $objcect->setPro($value) 来代替 $object->pro = $value 。 这在功能上是完全一样的效果,但是避免了使用 __get() 和 __set() ,相当于绕过了遍历的过程。

这里估计有人该骂我了,Yii好不容易实现了属性的机制,就是为了方便开发者, 结果我却在这里教大家怎么使用原始的方式,去提高所谓的效率。 嗯,确实,开发的便利性与执行高效率存在一定的矛盾。我个人的观点更倾向于以便利为先, 用好、用足Yii为我们创造的便利条件。至于效率的事情,更多的是框架自身需要注意的, 我们只要别写出格外2的代码就OK了。

不过你完全可以放心,在Yii的框架中,极少出现 $app->request 之类的代码,而是使用 $app->getRequest() 。 换句话说,框架自身还是格外地注重效率的,至于便利性,则留给了开发者。 总之,这里只是点出来有这么一个知识点,至于用不用,怎么用,完全取决于你了。

值得注意的是:

由于自动调用 __get() __set() 的时机仅仅发生在访问不存在的成员变量时。 因此,如果定义了成员变量 public $title 那么,就算定义了 getTitle() setTitle() , 他们也不会被调用。因为 $post->title 时,会直接指向该 pulic $title , __get() __set() 是不会被调用的。从根上就被切断了。
由于PHP对于类方法不区分大小写,即大小写不敏感, $post->getTitle() 和 $post->gettitle() 是调用相同的函数。 因此, $post->title 和 $post->Title 是同一个属性。即属性名也是不区分大小写的。
由于 __get() __set() 都是public的, 无论将 getTitle() setTitle() 声明为 public, private, protected, 都没有意义,外部同样都是可以访问。所以,所有的属性都是public的。
由于 __get() __set() 都不是static的,因此,没有办法使用static 的属性。
Object的其他与属性相关的方法

除了 __get() __set() 之外, yii\base\Object 还提供了以下方法便于使用属性:

__isset() 用于测试属性值是否不为 null ,在 isset($object->property) 时被自动调用。 注意该属性要有相应的getter。

__unset() 用于将属性值设为 null ,在 unset($object->property) 时被自动调用。 注意该属性要有相应的setter。

hasProperty() 用于测试是否有某个属性。即,定义了getter或setter。 如果 hasProperty() 的参数 $checkVars = true (默认为true), 那么只要具有同名的成员变量也认为具有该属性,如前面提到的 public $title 。

canGetProperty() 测试一个属性是否可读,参数 $checkVars 的意义同上。只要定义了getter,属性即可读。 同时,如果 $checkVars 为 true 。那么只要类定义了成员变量,不管是public, private 还是 protected, 都认为是可读。

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

Believe you or I have more or less understood that these three features are important entry points for enriching and expanding class functions and changing class behavior. 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 also 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:

Yii2.0 framework introduction and practical project development video tutorial

Yii2 Chinese manual

Build your own PHP framework from scratch

The above is the detailed content of Property in PHP's Yii framework. 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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

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

Video Face Swap

Video Face Swap

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

Hot Tools

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft