我一直坚持一个似乎很简单的命令连接,但无法解决它。
我有between()
函数执行以下操作:
/**
* Checks if passed int is between $left and $right
* @param int $left lowest value
* @param int $right highest value
* @param int $value actual value
* @return bool is $value between $left and $right
*/
function between($left, $right, $value)
{
$value = intval($value);
return ( $value >= $left && $value <= $right );
}
用法非常简单:
$int = 9;
var_dump( between( 6, 14, $int ) );//bool(true)
现在我想要实现的是:
$int = 9;
var_dump( $int.between( 6, 14 ) );//bool(true)
它会更有意义,也更容易理解。
任何想法我如何实现这一目标?
如果$int
是一个扩展了comparisonFunctions的对象,我可以做$int->between();
但也许有办法捕捉到什么。加入?
提前致谢
答案 0 :(得分:5)
.
运算符在Javascript和PHP中具有不同的含义:在Javascript中,它用于property accessor,而PHP将其用于string concatenation。对于PHP中的属性访问,您可以使用->
operator on objects(和::
operator on classes)代替。
因此,为了获得相同的行为,您需要使用这样的方法而不是scalar value来获取对象值:
class Integer {
private $value;
public function __constructor($value) {
$this->value = intval($value);
}
public function between($min, $max) {
if (!($min instanceof Integer)) {
$min = new Integer($min);
}
if (!($max instanceof Integer)) {
$max = new Integer($max);
}
return $min->intValue() <= $this->value && $this->value <= $max->intValue();
}
public function intValue() {
return $this->value;
}
}
然后你可以这样做:
$int = new Integer(9);
var_dump($int->between(6, 14));
但是,如果您只是正确命名函数并切换参数顺序,那么它可能已经足够了:
isInRange($val, $min, $max)
答案 1 :(得分:4)
$int
是基本类型int
并包含值9.它不是具有实例方法/函数的对象。这(遗憾地)不是Ruby;)
你想要的东西在PHP中是不可能的,除非你做这样的事情 - 但我不建议:
class Integer {
private $value;
public function __construct($value) {
$this->setValue((int)$value);
}
public function getValue() {
return $this->value;
}
public function setValue($value) {
$this->value = $value;
}
public function between($a, $b) {
return ($this->getValue() >= $a && $this->getValue() <= $b);
}
}