Re: Possible for class to return boolean?
Rik Wasmus wrote:
> On Thu, 27 Mar 2008 14:33:35 +0100, wswilson <wswilson@gmail.com> wrote:
>
>> Suppose I have:
>>
>> class A {
>> function __construct() {
>> $this->val = true;
>> }
>> }
>>
>> $a = new A();
>>
>> if ($a) {
>> echo 'some text';
>> }
>>
>> When I test "if ($a)", I want the class A to respond with the value of
>> $this->val, which is true at the moment.
>>
>> Is this possible?
>
> Nope, that kind of overloading cannot be done in PHP atm.
> What you can do is:
> - control how an object is evaluated in a string context with the magic
> __toString() function.
> - you can have some control over how an object is evaluated in an array
> context with for instance
> <http://www.php.net/~helly/php/ext/spl/classArrayIterator.html>
>
> ... however, for boolean castings default type casting applies, see
> <http://nl2.php.net/manual/en/language.types.boolean.php#language.types.boolean. casting>
>
>
> Given no further context, I see no clear reason why you can't call
> if($a->val) instead of if($a).
Where has he defined $val? Shouldn't he have declared it as a class
variable? Given that (and declared private since it doesn't make much
sense to declare a class value as public from an data hiding point of
view) he would need an accessor function like getVal() { return
$this->val; } and call if($a->getVal()) .
|