2014-09-03 2 views
0

주어진 유형의 속성을 필요로하는 클래스/객체를 생성 할 수 있습니까? 예를 들어, 다음과 같은 것 등 예외, 경고, 오류를 통해PHP는 주어진 유형의 객체 속성을 요구합니다

$bla = new bla(); 
$bla->integer_only="not an integer"; 

class bla { 
    public $array_only; 
    public $string_only; 
    public $integer_only; 
} 
+0

공개로 설정하지 않은 경우 : 비공개이거나 보호되어 있고 setter 메소드를 통해서만 설정할 수있는 경우 설정자 –

+0

@ MarkBaker에서 해당 규칙을 시행 할 수 있습니다. 고마워. 비공식으로 이해합니다. 보호받는다면 시행 될 수 있습니까? – user1032531

+0

보호 된 경우 자식 클래스는 setter 메서드를 쉽게 무시할 수 있습니다. – Crackertastic

답변

0

예는 유형이 스칼라 아니므로 너무 오래 함수 매개 변수에 입력 한 힌트를 사용할 수 또는에서 PHP의 getType로() 메소드를 사용하여 생성자. 이 같은 것도 효과가 있습니다.

if(is_int($value)){ 
    // all is good 
} 
+0

정교하게하십시오. – user1032531

+0

if (gettype ($ value)! = "정수") { // 여기서 오류를 던지십시오. } – Coldstar

1

할당 된 값의 데이터 유형을 확인할 수 있습니다. 변수에 특정 데이터 유형 만 지정하도록 할 수는 없습니다.

+0

참으로 참입니다. – Coldstar

0

개인 변수로 기본 클래스를 만든 다음 필요에 따라 형식을 확인하고 예외를 throw하는 public 및/또는 protected setter 메서드를 만드는 것이 좋습니다. 다음 고려 :

<?php 

class Foo 
{ 
    private $intValue; 
    private $strValue; 
    private $arrayValue; 

    protected function setInt($int) 
    { 
     if(is_int($int)) { 
      $this->intValue = $int; 
     } else { 
      throw new InvalidArgumentException; 
     } 
    } 

    protected function setString($str) 
    { 
     if(is_string($str)) { 
      $this->strValue = $str; 
     } else { 
      throw new InvalidArgumentException; 
     } 
    } 

    protected function setArray(array $arr) 
    { 
     //No need to check, type hint in method signature will enforce array 
     $this->arrayValue = $arr; 
    } 

    // Be sure to add your getter methods as well!!!! 
    // ..... 
} 

class Bar extends Foo 
{ 
    public function setValues($int, $str, $arr) 
    { 
     $this->setInt($int); 
     $this->setString($str); 
     $this->setArray($arr); 
    } 
} 

?> 

Foo 클래스는 부모 클래스입니다 만 정확한 유형이 private 변수로 할 것을 확인합니다. Bar은 자식이므로 보호 된 setter 메서드를 사용할 수는 있지만 형식을 직접 할당 할 수는 없습니다. 다음 코드 :

$bar = new Bar(); 
$bar->setValues(0, "We the people...", array("banana", "apple", "orange")); 
var_dump($bar); 

는 생산 :

object(Bar)[1] 
    private 'intValue' (Foo) => int 0 
    private 'strValue' (Foo) => string 'We the people...' (length=16) 
    private 'arrayValue' (Foo) => 
    array (size=3) 
     0 => string 'banana' (length=6) 
     1 => string 'apple' (length=5) 
     2 => string 'orange' (length=6) 

당신이 잡을 치명적인 오류 또는 InvalidArgumentException로 박았 구만 얻을 것이다 적절한 int, string, 또는 array 가치를 제공하지 않는 경우. 기본적으로 규칙을 준수하지 않으면 코드가 충돌을 일으 킵니다.

관련 문제