Is it possible to dynamically determine public default class variables from an array in php?

I have an event class that I use to insert / update data into my database. Is there a way so that I can create public variables from my db_fields array so that I don't have to duplicate data?

This is my current structure that works ...

class event{ protected static $table_name='tName'; protected static $db_fields = array('field1','field2','field3','field4','field5'); public $field1; public $field2; public $field3; public $field4; public $field5; } 

I would like to have something like this.

 class event{ protected static $table_name='tName'; protected static $db_fields = array('field1','field2','field3','field4','field5'); function __construct() { create_public_vars_here($db_fields); } } 

Thanks!

+4
source share
3 answers

You can try the following:

 class event{ protected static $table_name='tName'; protected static $db_fields = array('field1','field2','field3','field4','field5'); function __construct() { foreach (self::$db_fields as $var) { $this->$var = $whateverDefaultValue; } // After the foreach loop, you'll have a bunch of properties of this object with the variable names being the string values of the $db_fiels. // For example, you'll have $field1, $field2, etc and they will be loaded with the value $whateverDefaultValue (probably want to set it to null). } } 
+1
source

You can use magic setters / getters:

 class event{ protected static $table_name='tName'; protected static $db_fields = array('field1','field2','field3','field4','field5'); public function __get($key) { if(!in_array($key, static::$db_fields)) throw new Exception( $key . " doesn't exist."); return $this -> $key; } public function __set($key, $value) { if(!in_array($key, static::$db_fields)) throw new Exception( $key . " doesn't exist."); $this -> $key = $value; } } 

This way you will not hit values ​​outside of your list:

 $event -> field1 = 'hello'; // --> OK $event -> field17 = 'hello'; // --> Exception: field17 doesn't exist echo $event -> field1; // --> OK echo $event -> field17; // --> Exception: field17 doesn't exist 

As for having an explicit declaration of a public variable in your code, you do not need to if you do not need to iterate over your objects, but in this case you would execute an Iterator based on your static field.

+2
source

Use mutators:

 class event{ protected static $table_name='tName'; protected static $db_fields = array('field1','field2','field3','field4','field5'); function getVars($var) { if(!in_arrary($this->db_fields[$var])) { return false; } else { return $this->db_fields[$var]; } } } 

And then you can access it as follows:

 $eventObject->getVars('field3'); 

Or, if you are not creating an object outside the class:

 event::getVars('field3'); 

EDIT: in the spirit of complicating things so that you don't have a violation of boundaries, code has been added.

0
source

Source: https://habr.com/ru/post/1437687/


All Articles