반응형
매개 변수가 있는 PHP 생성자
다음과 같은 기능이 필요합니다.
$arr = array(); // This is the array where I'm storing data
$f = new MyRecord(); // I have __constructor in class Field() that sets some default values
$f->{'fid'} = 1;
$f->{'fvalue-string'} = $_POST['data'];
$arr[] = $f;
$f = new Field();
$f->{'fid'} = 2;
$f->{'fvalue-int'} = $_POST['data2'];
$arr[] = $f;
제가 이런 글을 쓸 때:
$f = new Field(1, 'fvalue-string', $_POST['data-string'], $arr);
$f = new Field(2, 'fvalue-int', $_POST['data-integer'], $arr);
// Description of parameters that I want to use:
// 1 - always integer, unique (fid property of MyRecord class)
// 'fvalue-int' - name of field/property in MyRecord class where the next parameter will go
// 3. Data for field specified in the previous parameter
// 4. Array where the class should go
저는 PHP에서 매개 변수화된 생성자를 만드는 방법을 모릅니다.
이제 저는 다음과 같은 생성자를 사용합니다.
class MyRecord
{
function __construct() {
$default = new stdClass();
$default->{'fvalue-string'} = '';
$default->{'fvalue-int'} = 0;
$default->{'fvalue-float'} = 0;
$default->{'fvalue-image'} = ' ';
$default->{'fvalue-datetime'} = 0;
$default->{'fvalue-boolean'} = false;
$this = $default;
}
}
생성자는 PHP의 다른 함수나 메서드처럼 매개 변수를 사용할 수 있습니다.
class MyClass {
public $param;
public function __construct($param) {
$this->param = $param;
}
}
$myClass = new MyClass('foobar');
echo $myClass->param; // foobar
이제 생성자를 사용하는 방법에 대한 예제는 재할당할 수 없기 때문에 컴파일조차 되지 않습니다.$this
.
또한 속성에 액세스하거나 설정할 때마다 괄호가 필요하지 않습니다.$object->property
잘 작동합니다.방법을 평가해야 하는 경우와 같은 특수한 상황에서만 곱슬 괄호를 사용하면 됩니다.$object->{$foo->bar()} = 'test';
배열을 매개 변수로 전달하고 속성을 '자동'으로 채우려면 다음을 수행합니다.
class MyRecord {
function __construct($parameters = array()) {
foreach($parameters as $key => $value) {
$this->$key = $value;
}
}
}
생성자는 객체를 만들고 초기화하는 데 사용되므로 사용할 수 있습니다.$this
구성하는 개체를 사용하거나 수정할 수 있습니다.
언급URL : https://stackoverflow.com/questions/9346856/php-constructor-with-a-parameter
반응형
'programing' 카테고리의 다른 글
결과 집합에서 문자 집합을 가져오는 방법은 무엇입니까? (0) | 2023.07.31 |
---|---|
도커 데몬 로그는 어디에 있습니까? (0) | 2023.07.31 |
외부 Javascript 파일에서 PHP var 액세스 (0) | 2023.07.26 |
목록의 *모든* 항목에 대한 장고 필터 쿼리 집합 __in (0) | 2023.07.26 |
Oracle SQL 개발자에서 사용자를 생성하는 방법 (0) | 2023.07.26 |