How to check if a model has a specific property or not?

I want to create one new model class, which will be expanded in all other classes. I want to automatically set some fields when the administrator adds / edits any record. those. createdDate, createdIp, updatedDate, updatedIp..etc.

Now all my questions will not be common in all models. Therefore, I want to check whether the createDate property has been created by the object, and only set its value. If there is no condition, and the model did not create a Date element, then it will generate an error. Below is the code I'm trying. But it does not work.

public function beforeSave() { if(isset($this->createdDate)) die('this model have createdDate field'); else die('this model does not have createdDate field'); } 

The model may not be direct; it may automatically extend the class associated with the database table. The object is printed below. createdDate is in a closed list.

If I use var_dump(property_exists($this, 'createdDate')); he gives me false.

 AdvertisementRate Object ( [bannerLocation_search] => [bannerType_search] => [_md:private] => CActiveRecordMetaData Object ( [tableSchema] => CMysqlTableSchema Object ( [schemaName] => [name] => tbl_advertisement_rate [rawName] => `tbl_advertisement_rate` [primaryKey] => advertisementRateId [sequenceName] => [columns] => Array ( [createdDate] => CMysqlColumnSchema Object ( [name] => createdDate [rawName] => `createdDate` [allowNull] => [dbType] => datetime [type] => string [defaultValue] => [size] => [precision] => [scale] => [isPrimaryKey] => [isForeignKey] => [autoIncrement] => [_e:private] => [_m:private] => ) 

Please help me add this logic.


yes .. CActiveRecord extends to my class.

MasterAdmin.php

 class MasterAdmin extends CActiveRecord { public function beforeSave() { echo '<pre>'; var_dump(property_exists($this, 'createdDate')); exit; } } 

User.php

 class User extend MasterAdmin { // So whenever any record added or edited, beforeSave will be called and i can autoset createddate value. } 
+4
source share
2 answers

property_exists() is what you are looking for.

Thus, if the property exists, but is NULL , the above function will return true, as expected, while isset() will return false, leading to the conclusion that the property does not exist.

It works for me. See example

+4
source

All Articles