The CActiveRecord __get method in PHP is used to retrieve the value of a specific attribute of an active record model. It is a magic method that is automatically called when an attempt is made to access a property or attribute that does not exist or is not defined in the model.
Example 1:
Suppose we have an active record model called User, with attributes 'id', 'name', and 'email'. To retrieve the value of the 'email' attribute using the __get method, we can write:
$user = User::model()->findByPk($id);
$email = $user->email;
In this example, the __get method is automatically called to retrieve the value of the 'email' attribute when it is accessed using the -> operator.
Example 2:
Another example of using the __get method in an active record model is to define a virtual attribute that is calculated based on other attributes. For instance, suppose we have an active record model called Product, with attributes 'id', 'name', 'price', and 'discount'. To calculate the discounted price of a product, we can define a virtual attribute called 'discounted_price' as follows:
In this example, the __get method is overridden to define the behavior of the virtual attribute 'discounted_price', which is calculated based on the 'price' and 'discount' attributes of the model. The round function is used to round the discounted price to 2 decimal places.
Package/Library:
The CActiveRecord is a part of the Yii framework, which is a high-performance PHP framework for developing web applications. The CActiveRecord class provides an easy-to-use and flexible way to interact with the database, by encapsulating the data access layer in an object-oriented way.
PHP CActiveRecord::__get - 21 examples found. These are the top rated real world PHP examples of CActiveRecord::__get extracted from open source projects. You can rate examples to help us improve the quality of examples.