Implementing isset() in a setter method
Is there any way to implement isset()
in a setter method? That is, hav开发者_运维技巧e the setter method check if the variable exists? From what I can tell no, but hopefully someone can confirm that for me. In a nutshell, I'm looking to avoid having to do
if (isset($arr[0])) $foo->setId($arr[0])
and simply just do
$foo->setId($arr[0])
and somehow implement the isset()
logic in the setter method. Thanks!
No, you not can subscript a missing array element and expect it to work. The subscript will be evaluated before being sent to the method. This means the subscript will fail before the method even receives the argument.
Example
$arr = array(0 => 'a', 1 => 'b', 2 => 'c');
If I do $foo->setId($arr[0])
then $foo->setId()
will receive a
as a string, and it will never know it was subscripted from an array (not does it want to know).
So a $foo->setId($arr[3])
would give an error...
Undefined offset
No.
You're only passing the value of $arr[0]
to the setter method, not the $arr[0]
variable. $foo::setId
has no idea of the existence of $arr
or $arr[0]
, all it gets to see is its value.
And that's a good thing for encapsulation! Imagine if every function would have to check if its parameters actually existed:
function setId($id) {
// $id is defined, it's required (has no default value),
// and yet I can't be sure it actually exists here...?
}
You'll have to check if the variable exists before passing its value to a function.
First, read @alex's answer. (Edit: Read @deceze's answer, too)
In order to mimic what you want you can pass the array and the index separately:
$foo->setId($arr, 0);
And change the setId()
method's signature (or add a safeSetId()
):
function safeSetId($array, $index) {
if (isset($array[$index])) {
$this->setId($array[$index]);
}
}
This is not very pretty, though :)
Isset
is not a function: it's a language construct. Language constructs are allowed to do magic; user-defined functions cant.
There is no way to reimplement the isset
logic without isset
itself (without modifications to PHP's source code, at least). If you try to implement it inside a function, the argument you receive will be null
if the variable doesn't exist and a E_NOTICE
error will be raised before your function is even called.
While you can't achieve what you're looking to do for reasons already given, you could still make the code more terse for very little overhead.
If the setId() function can handle null or if it is simply setting a member variable (which will by default be initialized to null), you could write a simple utility function like this:
function getValue($array, $key, $default = null) {
return isset($array[$key]) ? $array[$key] : $default;
}
and then call your setter like so:
$foo->setId(getValue($arr,0));
Again, there are drawbacks due to increased overhead and potential errors if your setter method expects a non-null value but this could decrease the amount of code slightly.
精彩评论