Gabriel Theron
Gabriel Theron

Reputation: 1376

Php: simple code validation failure

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.

Upvotes: 0

Views: 141

Answers (3)

Anti
Anti

Reputation: 458

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

Upvotes: 1

Aron Rotteveel
Aron Rotteveel

Reputation: 83173

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

Upvotes: 7

dan-lee
dan-lee

Reputation: 14502

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

Upvotes: 3

Related Questions