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.


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

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

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

    链接地址: http://www.djcxy.com/p/96562.html

    上一篇: 在php中从txt文件获取值

    下一篇: PHP:简单的代码验证失败