클래스 기본 공개 변수는 PHP의 배열에서 동적으로 정의 될 수 있습니까?
-
13-12-2019 - |
문제
데이터베이스에 데이터를 삽입 / 업데이트하는 데 사용하는 이벤트 클래스가 있습니다.데이터를 복제 할 필요가 없도록 내 db_fields 배열에서 공개 변수를 만들 수있는 방법이 있습니까?
이것은 내 현재의 구조입니다 ...
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;
}
.
나는 이와 같은 것을 갖고 싶습니다 ..
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);
}
}
.
감사합니다!
해결책
다음을 시도 할 수 있습니다.
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).
}
}
. 다른 팁
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;
}
}
.
이렇게하면 목록 이외의 값을 누르지 마십시오.
$event -> field1 = 'hello'; // --> OK
$event -> field17 = 'hello'; // --> Exception: field17 doesn't exist
echo $event -> field1; // --> OK
echo $event -> field17; // --> Exception: field17 doesn't exist
.
코드에서 명시 적 공개 변수 선언을 사용하는 것과 같이, 객체를 반복 할 필요가없는 한 필요가 없지만이 경우 Iterator
static 필드를 기반으로 인터페이스
뮤텍터 사용 :
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];
}
}
}
.
다음과 같이 액세스 할 수 있습니다 :
$eventObject->getVars('field3');
.
또는 클래스에서 객체를 만드는 경우 :
event::getVars('field3');
.
편집 : 경계를 위반하지 않도록 사물을 복잡하게하는 정신으로 코드가 추가되었습니다.
제휴하지 않습니다 StackOverflow