Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Usage of the Conditional Ternary operator to reduce brace and newline waste when processing optional method parameters
<?php
class Coordinate
{
protected $x;
protected $y;
public function __construct($x = null, $y = null)
{
(empty($x)) ?: $this->setX($x);
(empty($y)) ?: $this->setY($y);
}
/* What we're trying to replace
public function __construct($x = null, $y = null)
{
if ($x) {
$this->setX($x);
}
if ($y) {
$this->setY($y);
}
}
*/
public function setX($x)
{
$this->x = $x;
}
public function setY($y)
{
$this->y = $y;
}
}
@konrness

This comment has been minimized.

Copy link

konrness commented Mar 4, 2011

How is this any better/worse than:

if ($x) $this->setX($x);
@ralphschindler

This comment has been minimized.

Copy link
Owner Author

ralphschindler commented Mar 4, 2011

It's not. I think our coding standard has always shunned brace-less if statements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.