0

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?

1

2 Answers 2

5

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")
    );
}
Sign up to request clarification or add additional context in comments.

3 Comments

this one is short and nice solution.+1
i guess just twiddling the code formatter is as good idea as any
+1 for array constants. Note that these require PHP 5.6 or later, which shouldn't be an issue these days.
3

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.