Type Object in PHP

Asked

Viewed 78 times

5

I’m practicing some code in PHP when I come across this:

<?php
$a = (object) ["a" => "b"];
$b = (object) ["a"  => "c"];

$y = $a <=> $b;
echo $y;
$v=[1,2,3] <=> [1,2,3];
echo $v;
$a= (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b;
echo ($y == -1)? 1:0;
?>

Since I haven’t practiced PHP for a long time, my doubts are as follows::

  1. Why the exits of the first three echo are being respectively, -1,0,0?

  2. How I do this conversion ["a" => "b"] type-to-object?

  3. What’s the name of it <=>? comparison operator? Equality? I searched in the php.net I didn’t find anything on that.

1 answer

5


Why the exits of the first three echo are being respectively, -1,0,0?

According to the definition of the comparison operator (see below) are the expected results. In the first, the left operand is smaller, i.e., the letter b is smaller than the letter c. In the others the values are identical, therefore the result is 0.

How I do this conversion ["a" => "b"] type-to-object?

Did it the right way, albeit with questionable utility.

What’s the name of it <=>? comparison operator? Equality? I searched on php.net I didn’t find anything on that.

Behold: What are the "Spaceship Operator" <=> of PHP7?.

$a = (object)["a" => "b"];
$b = (object)["a"  => "c"];
$y = $a <=> $b;
echo $y;
$v=[1,2,3] <=> [1,2,3];
echo $v;
$a= (object)["a" => "b"];
$b = (object)["a" => "b"];
echo $a <=> $b;
echo ($y == -1)? 1:0;
var_dump($a);

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.