-1

I have my class with private property, but at insertion it does not insert anything. Fields are empty. Why is this happening? the magic method does not treat my values?

My class:

class Test extends Model {

  protected $table = 'test';
  private $name;
  private $email;

  public function __get($var) {
    return $this->$var;
  }

  public function __set($var, $values) {
    return $this->$var;
  }

  public function insert() {

    $sql    = "INSERT INTO {$this->table} (name, email) VALUES (:name, :email)";
    $stmt   = DB::prepare($sql);
    $stmt->bindParam(':name', $this->name);
    $stmt->bindParam(':email', $this->email);
    return $stmt->execute();

  }

}

$name               = 'Michael';
$email              = 'test@test.com';
$test               = new Test();
$test->name         = $name;
$test->email        = $email;

$test->insert();
Mourinha
  • 49
  • 6

1 Answers1

2

I'll answer to the scope of your question. Your issue lies within the __set() method.

You notice how you aren't actually "setting" anything? rather just running it as you would the __get() method? (returning the $var).

What you want it to look like is this:

public function __set($var, $values) {
    $this->$var = $values;
}

Notice how we finally assign something there?! That's the magic you want, and need.

Example


Foot-notes

Please read John Conde's comment, to prevent coding yourself into some ugly holes.

Community
  • 1
  • 1
Darren
  • 13,050
  • 4
  • 41
  • 79
  • @Mourinha No worries, [`This`](http://stackoverflow.com/q/4361553/2518525) Will be a great resource for you in relation to Public vs Private vs Protected. – Darren Aug 04 '14 at 02:17