How do I make a property private in a Laravel Eloquent Model?

eloquent, laravel, php

Solution

Try to override `__get(){}` and `__set(){}` magic methods, so it will be something like that:

class User extends Model
{
  protected $privateProperties = ['name'];

  public function __get($varName) {
      $this->isPrivate($varName);

      return parent::__get($varName);
  }

  public function __set($varName, $value) {
      $this->isPrivate($varName);

      return parent::__set($varName, $value);
  }

  protected function isPrivate($varName) {
      if (in_array($varName, $this->privateProperties)) {
          throw new \Exception('The ' . $varName. ' property is private');
      }
  }
}

Problem

Seems almost too obvious, but how do I make a class property private: ``` class User extends Model { private $name; // or protected } $user = new User(); $user->name = "Mrs. Miggins"; // <- I want this to generate an error echo $user->name; // Mrs. Miggins, (this too) ``` This is Laravel 5.1

Original source

Related problems