Constructor PHP con parámetro
Necesito una función que haga algo como esto:
$arr = array(); // this is array where im 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;
Cuando escribo algo como esto:
$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 next parameter will go
// 3. Data for field specified in previous parameter
// 4. Array where should class go
No sé cómo hacer constructor parametrizado en PHP.
Ahora uso constructor como este:
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;
}
}
2 answers
Leer todo esto http://www.php.net/manual/en/language.oop5.decon.php
Los constructores pueden tomar parámetros como cualquier otra función o método en php
class MyClass {
public $param;
public function __construct($param) {
$this->param = $param;
}
}
$myClass = new MyClass('foobar');
echo $myClass->param; // foobar
Tu ejemplo de cómo usas constructores ahora ni siquiera compilará ya que no puedes reasignar $this
.
Además, no necesita los corchetes cada vez que accede o establece una propiedad. $object->property
funciona muy bien. Solo necesita usar corchetes en circunstancias especiales, como si necesita evaluar un método $object->{$foo->bar()} = 'test';
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-04 15:03:15
Si desea pasar un array como parámetro y' auto ' rellenar sus propiedades:
class MyRecord {
function __construct($parameters = array()) {
foreach($parameters as $key => $value) {
$this->$key = $value;
}
}
}
Observe que se usa un constructor para crear e inicializar un objeto, por lo tanto se puede usar $this
para usar / modificar el objeto que está construyendo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-19 05:06:13