2016-07-03 2 views
-1

누군가 나에게이 코드를 설명 할 수주십시오

<?php 

class Model 
{ 

    protected $dates = []; 

    public function __get($property) 
    { 
     if (in_array($property, $this->dates)) { 
      return new DateTime($this->{$property}); 
     } 

     return $this->{$property}; 
    } 

} 

class User extends Model 
{ 
    protected $dates = ['createdAt']; 

    protected $createdAt = '2016-01-01 12:35:15'; 
} 

class Comment extends Model 
{ 
    protected $dates = ['createdAt']; 

    protected $createdAt = '2016-01-01 12:35:15'; 
} 

$comment = new Comment; 

var_dump($comment->createdAt->format('H:i')); 

나는 그가 여기에 배열을 사용하는 방법을하지 않습니다. 그는 $ property를 사용하여 배열의 인덱스에 액세스하고 있습니까? 그리고 $ this -> {$ property}는 어떻게 작동합니까?

재미 있지만 그냥 초보자 예를 들어, 비록 내가이 코드를 이해하지 ...

종류와 관련, 밀라노

+4

코드를 설명하도록 요청하는 질문이 [so]에서 ​​허용되지 않으므로이 질문을 주제와 관련이없는 것으로 닫으려고합니다. –

답변

3

그는 배열을 사용하는 방법을 나는하지 않는다 이리.

He/She는 dates 배열을 사용하여 날짜 속성 값을 적절한 DateTime 개체로 자동 변환합니다. 속성이 $this->dates 배열의 요소 중 하나와 일치하면 속성 값은 DateTime 값으로 반환되고 그렇지 않으면 일반 속성 값이 반환됩니다.

$ this -> {$ property}은 어떻게 작동합니까?

이 당신이 쓰레기 코드 상점 인 객체

// let's say $property is set to 'foo' 
$this->{$property} 

// is the same as 
$ths->foo 

에 동적 속성에 액세스하는 방법입니다.

속성의 동적 가져 오기/설정은 특정 속성이 특별한 방식으로 동작한다는 것을 의미합니다. 모델 속성이 추가되면 PHP 클래스 속성으로 누수됩니다. 그것은 재앙을위한 처방이다.

여기에 더 나은 코드 예제를 이제 모든 설정/모델의 특성을 잘 하나 $this->attributes 배열 클래스 속성에 샌드 박스 얻을

Run this code at REPL.it

class Util { 
    static public function datetime($str) { 
    return new DateTime($str); 
    } 
} 

class Model { 
    protected $attributes = []; 

    protected $map_attributes = []; 

    public function __construct($attributes = []) { 
    $this->attributes = $attributes; 
    } 

    public function __set($property, $value) { 
    $attributes[$property] = $value; 
    } 

    public function __get($property) { 
    if (!array_key_exists($property, $this->attributes)) 
     return null; 
    elseif (array_key_exists($property, $this->map_attributes)) 
     return call_user_func($this->map_attributes[$property], $this->attributes[$property]); 
    else 
     return $this->attributes[$property]; 
    } 
} 

class User extends Model { 
    protected $map_attributes = [ 
    'created_at' => ['Util', 'datetime'] 
    ]; 
} 

$u = new User(['foo' => 'bar', 'created_at' => '2016-01-01 12:35:15']); 

echo $u->foo, PHP_EOL;      // bar 
echo $u->created_at->format('H:i'), PHP_EOL; // 12:35 
을합니다. 이렇게하면 재산이 모두 Model 또는 서브 클래스가 Model 이상이되는 것을 방지 할 수 있습니다.

또한 각 클래스는 적절한 매핑 함수를 $this->map_attributes에 설정하여 임의의 속성을 다른 값으로 임의로 매핑 할 수 있습니다. 즉, 하위 클래스가 다른 유형을 반환해야하는 경우 Model::__get을 업데이트하여 새 속성 -> 값 매핑을 지원하지 않아도됩니다.

따라서 추악하고 위험한 $this->{$property}도 사라집니다. 동적 속성 액세스에는 유스 케이스가 있지만, 게시 한 원본 코드가 그 중 하나라고 생각하지 않습니다.