I have this example pseudo-code that works, $x basically is an object with keys and values or array with keys and objects as values. $y will be constructed in two different ways.
private function someFunction($x) {
if (is_object($x)) {
$y = 'result of something';
} elseif (is_array($x)) {
$y = 'result of something';
} else {
$y = null;
}
return $y;
}
Is this a good practice, if function will not be used anywhere else? 'Non-hack' way probably is to convert object to an array (because it is an array in essence) and then make logic based on count of arrays.
Or am I just thinking to much about writing code 'right way'?
The way of using this function is acceptable as long as the input is controlled by you and you know what you are going to do with the data. However on inputs from uncontrolled sources from outside, you should validate the data beforehand as you would not know for sure if the data is valid.
What I don't understand is how you reach a point a variable may be two different types: an array or an object.
If you convert it to array and then process it, or use your own function, the important thing is that your logic flows and the code does what it is intended to do.
If context is right and the code does what it is intended to do, then your code is just fine.
In PHP this is actually the only way this is possible and I wouldn't call it bad practice in itself at least for type checking. In Java and other languages we have method overloading:
public String someFunction(Object $x) {
return "Result of something";
}
public String someFunction(Object[] $x) {
return "Result of something";
}
public String someFunction(int $y) {
return "Result of something";
}
In PHP, I'd suggest a similar separation of concerns like so:
private function someFunction($x) {
if (is_object($x)) {
$y = $this->someFunctionObject($x);
} elseif (is_array($x)) {
$y = $this->someFunctionArray($x);
} else {
$y = $this->someFunctionScalar($x);
}
return $y;
}
private function someFunctionObject($x) {
}
private function someFunctionArray($x) {
}
private function someFuctionScalar($x) {
}
The problem with a loosely typed language such as PHP is that there are actually types and sometimes you need to deal with them.
I'd argue that having to do a conversion every time someFunction is called is worse than doing the type check and conversion internally because repeated code is going to be more problematic than an if/else in one method.