Skip to content

Instantly share code, notes, and snippets.

@liyu001989
Last active October 8, 2016 02:26
Show Gist options
  • Save liyu001989/81d21facb7627fee7335afefa5d3b83f to your computer and use it in GitHub Desktop.
Save liyu001989/81d21facb7627fee7335afefa5d3b83f to your computer and use it in GitHub Desktop.
isset 再 php7 中出现的问题
<?php
class Model
{
// 存放属性
protected $attributes = [];
// 存放关系
protected $relations = [];
function __get($key)
{
if( isset($this->attributes[$key]) ) {
return $this->attributes[$key];
}
if (method_exists($this, $key)) {
return $this->getRelationshipFromMethod($key);
}
}
protected function getRelationshipFromMethod($method)
{
$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;
}
// 关键是这个处理 5.1.35 中没有, 注释这句就可以看到效果
if (method_exists($this, $key) && $this->$key && isset($this->relations[$key] )) {
return true;
}
return false;
}
}
class Post extends Model
{
protected function user()
{
$user = new User();
$user->name = 'user name';
return $user;
}
}
class User extends Model
{
}
$post = new Post();
echo '对象未赋值:';
echo isset($post->content) ? 'true' : 'false';
echo PHP_EOL;
$post->content = 'foobar';
echo '对象赋值:';
echo isset($post->content) ? 'true' : 'false';
echo PHP_EOL;
echo 'isset post 的 user 的名字:';
echo isset($post->user->name) ? 'true' : 'false';
echo PHP_EOL;
// 先赋值
echo 'post 的 user 的名字:';
echo $post->user->name;
echo PHP_EOL;
echo 'isset post 的 user 的名字:';
echo isset($post->user->name) ? 'true' : 'false';
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment