user8011997
user8011997

Reputation:

using an array as a class property in php

I tried to create a class with the properties like so:

class foo{

private $dbFields['test']=array("mobilePhone","address");
private $dbFields['test2']=array("mobilePhone","address",'colour');

}

but its not valid.

PHP Parse error: syntax error, unexpected '[', expecting ',' or ';' in

I had to do this which has the same result; but is less friendly for me editing in the future

class foo{

private $dbFields=array('test'=>array("mobilePhone","address"),'test2'=>array("mobilePhone","address",'colour'));

}

is there anyway to achieve the original structure or something simular?

Upvotes: 0

Views: 83

Answers (2)

Lawrence Cherone
Lawrence Cherone

Reputation: 46650

You can do it with the following class properties syntax:

<?php
class foo {
    private $dbFields = array(
        'test' => array("mobilePhone","address"),
        'test2' => array("mobilePhone","address","colour")
    );
}

If the values are dynamic, and not as it looks (like a reference to database columns), then you should pass the values to the class constructor as suggested by B.Desai answer.

And if the values never change perhaps using a class constant would be nicer (PHP >=5.3.0).

<?php
class foo {
    const dbFields = array(
        'test'  => array("mobilePhone","address"),
        'test2' => array("mobilePhone","address","colour")
    );
}

Upvotes: 5

B. Desai
B. Desai

Reputation: 16436

Always initialize class member in constructor. This way you can assign any dynamic value also to data member.

class foo{

private $dbFields;
function __construct()
{
  $this->dbFields['test']=array("mobilePhone","address");
  $this->dbFields['test2']=array("mobilePhone","address",'colour');
}
function getFields()
{
  return $this->dbFields;
}
}
$obj = new foo();
print_r($obj->getFields());

Upvotes: 3

Related Questions