gpt4 book ai didi

PHP 忽略类内的 __set 方法

转载 作者:可可西里 更新时间:2023-11-01 13:09:08 25 4
gpt4 key购买 nike

我正在构建一个包含多个输入验证的类,我决定将它们放在 __set 方法中(我不确定这是否是正确的形式,因为我的 OOP 经验有限)。这似乎工作正常,当从类外部传递无效值时抛出正确的错误。但是,如果在类中修改变量,则 _ _set 方法似乎会被完全忽略。

任何见解将不胜感激

//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/>";
}

最佳答案

阅读 __set 的定义:“__set() 在将数据写入不可访问的成员时运行。”无法访问是这里的关键。在类中,所有成员都可以访问,并且 __set 被绕过。 Overloading

关于PHP 忽略类内的 __set 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com