Kamil Kamil - 2 years ago 153
PHP Question

PHP constructor with parameter

I need function that will do something like this:

$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;

When i write something like this:

$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

I dont know how to make parametrized constructor in PHP.

Now i use constructor like this:

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;

Answer Source

Read all of this http://www.php.net/manual/en/language.oop5.decon.php

Constructors can take parameters like any other function or method in php

class MyClass {

  public $param;

  public function __construct($param) {
    $this->param = $param;

$myClass = new MyClass('foobar');
echo $myClass->param; // foobar

Your example of how you use constructors now won't even compile as you can't reassign $this.

Also, you don't need the curly brackets every time you access or set a property. $object->property works just fine. You only need to use curly-brackets under special circumstances like if you need to evaluate a method $object->{$foo->bar()} = 'test';

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download