<?php
class Post
{
protected $attributes = ['content' => 'foobar'];
public function __get($key)
{
if (isset($this->attributes[$key])) {
return $this->attributes[$key];
}
}
}
$post = new Post();
echo isset($post->content); // false
上面这个例子将永远返回 false,因为 foo 并不是 Post 的属性,而是 __get 取出来的
魔术方法 __isset
那么怎么解决上面那个问题呢?使用魔术方法
<?PHP
class Post
{
protected $attributes = ['content' => 'foobar'];
public function __get($key)
{
if (isset($this->attributes[$key])) {
return $this->attributes[$key];
}
}
public function __isset($key)
{
if (isset($this->attributes[$key])) {
return true;
}
return false;
}
}
$post = new Post();
echo isset($post->content); //true
类似 Eloquent 的例子
看着 laravel 5.1.35 的代码,我们自己写一个简单的例子
先有一个 Model,简单的实现。__get,__set,__isset
class Model
{
// 存放属性
protected $attributes = [];
// 存放关系
protected $relations = [];
public function __get($key)
{
if( isset($this->attributes[$key]) ) {
return $this->attributes[$key];
}
// 找到关联的对象,放在关系里面
if (method_exists($this, $key)) {
$relation = $this->$method();
return $this->relations[$method] = $relation;
}
}
public function __set($k, $v)
{
$this->attributes[$k] = $v;
}
public function __isset($key)
{
if (isset($this->attributes[$key]) || isset($this->relations[$key])) {
return true;
}
return false;
}
}
然后我们定义一个 Post Moel 和一个 User Moel
class Post extends Model
{
protected function user()
{
$user = new User();
$user->name = 'user name';
return $user;
}
}
class User extends Model
{
}
<?php
class Post
{
protected $attributes = ['content' => 'foobar'];
public function __get($key)
{
if (isset($this->attributes[$key])) {
return $this->attributes[$key];
}
}
}
$post = new Post();
echo isset($post->content); // false
上面这个例子将永远返回 false,因为 foo 并不是 Post 的属性,而是 __get 取出来的
魔术方法 __isset
那么怎么解决上面那个问题呢?使用魔术方法
<?PHP
class Post
{
protected $attributes = ['content' => 'foobar'];
public function __get($key)
{
if (isset($this->attributes[$key])) {
return $this->attributes[$key];
}
}
public function __isset($key)
{
if (isset($this->attributes[$key])) {
return true;
}
return false;
}
}
$post = new Post();
echo isset($post->content); //true
类似 Eloquent 的例子
看着 laravel 5.1.35 的代码,我们自己写一个简单的例子
先有一个 Model,简单的实现。__get,__set,__isset
class Model
{
// 存放属性
protected $attributes = [];
// 存放关系
protected $relations = [];
public function __get($key)
{
if( isset($this->attributes[$key]) ) {
return $this->attributes[$key];
}
// 找到关联的对象,放在关系里面
if (method_exists($this, $key)) {
$relation = $this->$method();
return $this->relations[$method] = $relation;
}
}
public function __set($k, $v)
{
$this->attributes[$k] = $v;
}
public function __isset($key)
{
if (isset($this->attributes[$key]) || isset($this->relations[$key])) {
return true;
}
return false;
}
}
然后我们定义一个 Post Moel 和一个 User Moel
class Post extends Model
{
protected function user()
{
$user = new User();
$user->name = 'user name';
return $user;
}
}
class User extends Model
{
}