PHP sınıf içinde __ set yöntemi göz ardı

2 Cevap php

Ben giriş doğrulamaları bir dizi ile bir sınıf inşa ediyorum ve ben (sınırlı cepten deneyime sahip olarak bu uygun form olup olmadığından emin değilim) bir __ set yöntemi içinde yerleştirmek için karar verdik. Bu geçersiz değerler sınıf dışında geçirilen zaman doğru hatalar atma, iyi iş gibi görünüyor. Değişken bir sınıf içinde değiştirilmiş Ancak, __ set yöntemi alltogether gözardı edilecek gibi görünüyor.

Herhangi bir fikir derece mutluluk duyacağız

//RESULT:::::::::::::::::::::::::::::::
// PASS: Testing : hello
// PASS: Testing exception handling
// __SET: Setting b to 123
// PASS: Testing with valid value: 123
// FAIL: Testing exception handling World2



 <?php
class Test {
        public $a;
        private $b;

        function __set( $key, $val ) {

                switch( $key ) {
                        case 'b':
                                if( !is_numeric( $val ) ) throw new Exception("Variable $b must be numeric");
                                break;
                }

                echo ( "__SET: Setting {$key} to {$val}<br/>" );
                $this->$key = $val;
        }
        function __get( $key ) { return $this->$key; }
        function bMethod() {
                $this->b = "World2";
        }

}

$t = new Test();

//testing a
try {
        $t->a = "hello";
        echo "PASS: Testing $a: {$t->a}<br/>";
} catch( Exception $e)  {
        echo "FAIL: Testing $a";
}

//testing b
try {
        $t->b = "world";       
        echo "FAIL: Testing $b exception handling<br/>";
} catch( Exception $e ){
        echo "PASS: Testing $b exception handling<br/>";
}

//testing b with valid value
try  {
        $t->b = 123;
        echo "PASS: Testing $b with valid value: {$t->b}<br/>";
} catch( Exception $e) {
        echo "FAIL: Testing $b";
}

//bypassing exception handling with method
try {
        $t->bMethod("world");
        echo "FAIL: Testing $b exception handling {$t->b}<br/>";
} catch( Exception $e ) {
        echo "PASS: Testing $b exception handling<br/>";
}

2 Cevap

Ulaşılmaz üyelerine veri yazarken) (_ set: " _set tanımı okuyun çalıştırılır. "Inaccessible burada anahtarıdır. Sınıfı içinde itibaren, tüm üyeler set atlanır erişilebilir ve __ vardır. {[(1)] }

php documentation at belgelerine diyor ki:

__get () erişilemez elemanından veri okumak için kullanılır.

Yani, sen gibi bir şey yapabilirsiniz:

<?php
class Test {
    private $_params = array();

    function __set( $key, $val ) {
        ...
        $this->_params[$key] = $val;
    }

    function __get( $key ) {
        if (isset($this->_params[$key])) return $this->$key;
        throw Exception("Variable not set");
    }

    ...
}