0

I'm currently working on a simple php function for an entity in the framework Symfony2. That function keeps generating errors, although I cannot see what is wrong. Here's the code :

public function getForm(array $reqFields){
    var $formHelper = new FormHelper;
    var $fields = new array;

    if($reqFields == null){
        foreach ($this->getArray() as $k => $v) {
            array_push($fields, $formHelper->getTextField($v, $k));
        }
    }

    return $formHelper->getForm($fields);
}

I've imported FormHelper, and the functions in it exist, for that matter. When I execute it, I get the following error:

Parse error: syntax error, unexpected T_VAR

What's the problem?

Edit: Netbeans tells me that $reqFields should be initialized (but it's an argument :/), and that an identifier is expected on the return line.

Gabriel Theron
  • 1,346
  • 3
  • 20
  • 49

3 Answers3

7

I notice two things at least:

  • Arrays are not objects. You cannot create an array instance like you do with new array.
  • The var keyword is deprecated as of PHP 5.3. (And you are using it wrong)

So your code:

var $formHelper = new FormHelper;
var $fields = new array;

Should become:

$formHelper = new FormHelper;
$fields = array();
Community
  • 1
  • 1
Aron Rotteveel
  • 81,193
  • 17
  • 104
  • 128
3

Arrays arent objects!
So it is:

var $fields = array();

And you have to define class variables in the class header not in the function. So you should erase var in front too.

Like this:

class Foo
{
   public $fields = array(); // var equals public (you should use public, because var is deprecated)

   public function bar()
   {
      print_r($this->fields); // => Array ( )
   }
}
dan-lee
  • 14,365
  • 5
  • 52
  • 77
1
public function getForm(array $reqFields){

in php you don't declare the parameters type so you should transform it in

public function getForm($reqFields){

or

public function getForm($reqFields = array()){

if yout want the parameter to be optional also

$formHelper = new FormHelper();

also

$fields = array();

also

foreach ($this->getArray() as $k => $v) {

I assume that $this is the form...if not use $formHelper->getData();

j0k
  • 22,600
  • 28
  • 79
  • 90
Anti
  • 458
  • 3
  • 8
  • 1
    Typehinting an array, callable or class name is possible in function definitions, see [documentation](http://php.net/manual/en/language.oop5.typehinting.php). – jkrcma Jun 15 '12 at 09:55