Ali
Ali

Reputation: 267077

PHP OOP Problem

This is my parent class:

class Model extends CI_Model
{
    protected $table, $idField='id';
    public $fields;

    function __construct()
    {
        parent::__construct();
        $this->fields  = new ValFieldGroup();
    }
    //Other Code
}

Here's the code of the ValFieldGroup class:

class ValFieldGroup
{
    private $fields = array();

    public function add($name, $rules = '', $label = '')
    {
        $this->fields[$name] = new ValField($name, $rules, $label);
    }

    public function __get($name)
    {
        if (isset($this->fields[$name]))
            return $this->fields[$name];
        else
            return false;
    }

    public function __set($name, $value)
    {
        $this->fields[$name] = $value;
    }

    public function getAll()
    {
        return $this->fields;
    }
}

Here's the child class where I'm getting an error:

class User extends Model
{
    function __construct()
    {
        parent::__construct();

        $this->fields.add('first', 'required', 'First Name');
        // Snip
    }
    // Snip
}

I'm getting the following error when I run this code:

Fatal error: Call to undefined function add() in \models\user.php..

Which is this line in the class User:

$this->fields.add('first', 'required', 'First Name');

When I do a print_r($this->fields) before this line, I get:

ValFieldGroup Object ( [fields:private] => Array ( ) )

So clearly the class is being setup but I can't use the function I want.. what am I doing wrong?

Upvotes: 2

Views: 141

Answers (3)

Gordon
Gordon

Reputation: 316989

Unless add is a function from the global scope, I'd say fields.add() should be fields->add(). The dot is the string concatenation operator in PHP.

Upvotes: 7

Neil Aitken
Neil Aitken

Reputation: 7854

You aren't calling the method correctly, try this:

class User extends Model
{
    function __construct()
    {
        parent::__construct();

        $this->fields->add('first', 'required', 'First Name');
        // Snip
    }
    // Snip
}

Upvotes: 2

Jeff Lambert
Jeff Lambert

Reputation: 24661

Your User class extends SuperModel, not Model.

Upvotes: 2

Related Questions