Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ralphschindler/854866 to your computer and use it in GitHub Desktop.
Save ralphschindler/854866 to your computer and use it in GitHub Desktop.
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
Copy link

konrness commented Mar 4, 2011

How is this any better/worse than:

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

@ralphschindler
Copy link
Author

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