새 속성을 동적으로 생성하는 방법
오브젝트의 메서드 내에 지정된 인수로 속성을 작성하려면 어떻게 해야 합니까?
class Foo{
public function createProperty($var_name, $val){
// here how can I create a property named "$var_name"
// that takes $val as value?
}
}
그리고 다음과 같은 방법으로 숙박시설에 액세스할 수 있기를 원합니다.
$object = new Foo();
$object->createProperty('hello', 'Hiiiiiiiiiiiiiiii');
echo $object->hello;
또한 재산을 공개/보호/사적으로 할 수 있습니까?이 경우 공개해야 한다는 것을 알고 있지만, 보호되는 속성 등을 얻기 위해 몇 가지 magik 메서드를 추가해야 할 수도 있습니다.
I think I found a solution:
protected $user_properties = array();
public function createProperty($var_name, $val){
$this->user_properties[$var_name] = $val;
}
public function __get($name){
if(isset($this->user_properties[$name])
return $this->user_properties[$name];
}
그게 좋은 생각일까요?
그것을 하는 데는 두 가지 방법이 있습니다.
하나는 클래스 외부에서 동적으로 속성을 직접 생성할 수 있습니다.
class Foo{
}
$foo = new Foo();
$foo->hello = 'Something';
또는 다음을 통해 자산을 생성하려는 경우createProperty
방법:
class Foo{
public function createProperty($name, $value){
$this->{$name} = $value;
}
}
$foo = new Foo();
$foo->createProperty('hello', 'something');
다음 예는 클래스 전체를 선언하지 않는 사용자를 위한 것입니다.
$test = (object) [];
$prop = 'hello';
$test->{$prop} = 'Hiiiiiiiiiiiiiiii';
echo $test->hello; // prints Hiiiiiiiiiiiiiiii
속성 오버로드가 매우 느립니다.가능하면 피하도록 하세요.다른 두 가지 마법 방법을 구현하는 것도 중요합니다.
__isset(); __set();
나중에 이러한 오브젝트 "속성"을 사용할 때 일반적인 실수를 발견하지 않으려면
다음은 몇 가지 예입니다.
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
Alex 코멘트 후 편집:
두 솔루션 간의 시간 차이를 직접 확인할 수 있습니다($REPEAT_PLEASE 변경).
<?php
$REPEAT_PLEASE=500000;
class a {}
$time = time();
$a = new a();
for($i=0;$i<$REPEAT_PLEASE;$i++)
{
$a->data = 'hi';
$a->data = 'bye'.$a->data;
}
echo '"NORMAL" TIME: '.(time()-$time)."\n";
class b
{
function __set($name,$value)
{
$this->d[$name] = $value;
}
function __get($name)
{
return $this->d[$name];
}
}
$time=time();
$a = new b();
for($i=0;$i<$REPEAT_PLEASE;$i++)
{
$a->data = 'hi';
//echo $a->data;
$a->data = 'bye'.$a->data;
}
echo "TIME OVERLOADING: ".(time()-$time)."\n";
$object->{$property} 구문을 사용합니다.$property는 문자열 변수이고 $object는 클래스 또는 인스턴스 오브젝트 내에 있는 경우 이 변수가 될 수 있습니다.
라이브 예:http://sandbox.onlinephpfunctions.com/code/108f0ca2bef5cf4af8225d6a6ff11dfd0741757f
class Test{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$test = new Test();
$test->createProperty('property1', '50');
echo $test->property1;
결과: 50
언급URL : https://stackoverflow.com/questions/8707235/how-to-create-new-property-dynamically
'source' 카테고리의 다른 글
길이가 같지 않은 두 리스트 간의 순열 (0) | 2022.10.20 |
---|---|
동일한 테이블에 있는 다른 열의 값과 동일한 한 열의 SQL 설정 값 (0) | 2022.10.20 |
PHP DateTime 마이크로초는 항상 0을 반환합니다. (0) | 2022.10.20 |
Python에서 목록의 키와 빈 값을 사용하여 dict를 초기화하려면 어떻게 해야 합니까? (0) | 2022.10.20 |
iOS에서의 Dellphi XE6 링크 C 코드 (0) | 2022.10.20 |