PHP 7의 속성에 대한 유형 힌트?
PHP 7은 클래스 속성에 대한 유형 힌트를 지원합니까?
내 말은, setter / getters 뿐만 아니라 속성 자체를 위해서 도요 .
다음과 같은 것 :
class Foo {
/**
*
* @var Bar
*/
public $bar : Bar;
}
$fooInstance = new Foo();
$fooInstance->bar = new NotBar(); //Error
PHP 7.4 는 다음과 같은 유형의 속성을 지원합니다 .
class Person
{
public string $name;
public DateTimeImmutable $dateOfBirth;
}
PHP 7.3 및 이전 버전은이를 지원하지 않지만 몇 가지 대안이 있습니다.
유형 선언이있는 getter 및 setter를 통해서만 액세스 할 수있는 개인 속성을 만들 수 있습니다.
class Person
{
private $name;
public function getName(): string {
return $this->name;
}
public function setName(string $newName) {
$this->name = $newName;
}
}
또한 공용 속성을 만들고 docblock을 사용하여 코드를 읽고 IDE를 사용하는 사람들에게 유형 정보를 제공 할 수 있지만 런타임 유형 검사는 제공하지 않습니다.
class Person
{
/**
* @var string
*/
public $name;
}
그리고 실제로 getter와 setter와 docblock을 결합 할 수 있습니다.
좀 더 모험적인 경우와 가짜 속성을 만들 수있는 __get, __set, __isset및 __unset마술 방법 및 종류를 직접 확인하십시오. 그래도 추천 할 수 있을지 모르겠습니다.
7.4 이상 :
@Andrea가 지적했듯이 새 릴리스에서 구현 될 것이라는 좋은 소식입니다. 누군가 7.4 이전에 사용하려는 경우이 솔루션을 여기에 남겨 두겠습니다.
7.3 이하
이 스레드에서 여전히 수신하는 알림을 기반으로 많은 사람들이 내가 가진 동일한 문제를 가지고 있다고 생각합니다. 이 경우에 대한 내 솔루션은 이 동작을 시뮬레이션하기 위해 특성 내부에 setter + __setmagic 메서드를 결합하는 것이 었습니다 . 여기있어:
trait SettersTrait
{
/**
* @param $name
* @param $value
*/
public function __set($name, $value)
{
$setter = 'set'.$name;
if (method_exists($this, $setter)) {
$this->$setter($value);
} else {
$this->$name = $value;
}
}
}
그리고 여기에 데모가 있습니다.
class Bar {}
class NotBar {}
class Foo
{
use SettersTrait; //It could be implemented within this class but I used it as a trait for more flexibility
/**
*
* @var Bar
*/
private $bar;
/**
* @param Bar $bar
*/
protected function setBar(Bar $bar)
{
//(optional) Protected so it wont be called directly by external 'entities'
$this->bar = $bar;
}
}
$foo = new Foo();
$foo->bar = new NotBar(); //Error
//$foo->bar = new Bar(); //Success
설명
First of all, define bar as a private property so PHP will cast __set automagically.
__set will check if there is some setter declared in the current object (method_exists($this, $setter)). Otherwise it will only set its value as it normally would.
Declare a setter method (setBar) that receives a type-hinted argument (setBar(Bar $bar)).
As long as PHP detects that something that is not Bar instance is being passed to the setter, it will automaticaly trigger a Fatal Error: Uncaught TypeError: Argument 1 passed to Foo::setBar() must be an instance of Bar, instance of NotBar given
It is actually not possible and you only have 4 ways to actually simulate it :
- Default values
- Decorators in comment blocks
- Default values in constructor
- Getters and setters
I combined all of them here
class Foo
{
/**
* @var Bar
*/
protected $bar = null;
/**
* Foo constructor
* @param Bar $bar
**/
public function __construct(Bar $bar = null){
$this->bar = $bar;
}
/**
* @return Bar
*/
public function getBar() : ?Bar{
return $this->bar;
}
/**
* @param Bar $bar
*/
public function setBar(Bar $bar) {
$this->bar = $bar;
}
}
Note that you actually can type the return as ?Bar since php 7.1 (nullable) because it could be null (not available in php7.0.)
You also can type the return as void since php7.1
You can use setter
class Bar {
public $val;
}
class Foo {
/**
*
* @var Bar
*/
private $bar;
/**
* @return Bar
*/
public function getBar()
{
return $this->bar;
}
/**
* @param Bar $bar
*/
public function setBar(Bar $bar)
{
$this->bar = $bar;
}
}
$fooInstance = new Foo();
// $fooInstance->bar = new NotBar(); //Error
$fooInstance->setBar($fooInstance);
Output:
TypeError: Argument 1 passed to Foo::setBar() must be an instance of Bar, instance of Foo given, called in ...
참고URL : https://stackoverflow.com/questions/37254695/type-hinting-for-properties-in-php-7
'program story' 카테고리의 다른 글
| 모든 최근 커밋을 표시하지 않는 "svn log" (0) | 2020.11.08 |
|---|---|
| 수평 스크롤바없이 부트 스트랩 3 유동 레이아웃을 만드는 방법 (0) | 2020.11.08 |
| “누락 된 마케팅 아이콘을 해결하는 방법. (0) | 2020.11.08 |
| SQL Server 2005에 비해 SQL Server 2008의 장점은 무엇입니까? (0) | 2020.11.08 |
| Android : AlarmManager로 설정된 모든 PendingIntents 가져 오기 (0) | 2020.11.07 |