开发者

Function on objects that return specific values when the object is cast

First of all, I apologize that this question is so vague. I can't remember what this is called, or how they work, so it's very difficult to start searching or formulate a good title.

I have two questions wrapped into one:

First:

How are objects converted to other types internally? What is this called?

Example:

$Obj{
    $value = 1;
    $other = 2;
    $more = 3;
}

$myObj = (string)$Obj;

print $myObj; // prints "1, 2, 3" or something like that

Second:

Can this method be used in math? Is there some override function that recognizes when an Object is being used in math?

Example:

$Obj{
        $value = 1;
        $other = 2;
        $more = 3;
    }

$result = 4 / $Obj;

print $result; // prints ".66666667" or something similar (sum of all properties)

Update:

I think it might have something to do with serialize(), but I know I've heard of a case where this is done "automatically" without having to call serialize() and it's done in a way that doesn't actually serialize the whole object, it just converts it to a useable value, like my above exam开发者_JAVA技巧ples.

Final:

Thanks for @trey for being right about it being casting and to @webbiedave for pointing me to the magic method __toString.


It is casting as you can define the magic method __toString to allow the object to be cast to a string as desired, which will then allow PHP to cast it to an int or float in math.

Take the following example:

class A
{
    public $value = 1;
    public $other = 2;
    public $more  = 3;

    public function __toString()
    {
        return (string)($this->value + $this->other + $this->more);
    }
}

$obj = new A();
echo 4 / (string)$obj; // outputs 0.66666666666667 


It's called type casting when you change an object to a different data type, as for the second part, I'm not entirely sure I understand you, are you trying to type cast during a math function?

it sounds like this may be more along the lines of what you're looking for:

class User
{
  public $first_name='John';
  public $last_name='Smith';

  public function __toString()
  {
    return "User [first='$this->first_name', last='$this->last_name']";
  }
}
 $user=new User;
 print '<span>'.$user.'</span>';

but I'm unable to find documentation about how to make this work when the object is converted to an interger... I'll update if I do

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜