开发者

making PHP join/concat (.) like JavaScript

I've stuck on a seems-to-be simple command join, but can't work it out.

I have a between() function which does the following:


/**
 * Checks if passed int is between $left and $right
 * @param int $left lowest value
 * @param int $right highest value
 * @param int $value a开发者_如何学编程ctual value
 * @return bool is $value between $left and $right
 */
function between($left, $right, $value)
{
    $value = intval($value);
    return ( $value >= $left && $value <= $right );
}

and the usage is pretty simple:

$int = 9;

var_dump( between( 6, 14, $int ) );//bool(true)

Now what I want to achieve is:


$int = 9;

var_dump( $int.between( 6, 14 ) );//bool(true)

it would make more sense and would be easier to understand.

Any ideas how do I achieve this?

If $int would be an object which extends comparisonFunctions I could do $int->between(); but maybe there is a way to catch what does . join?

Thanks in advance


The . operator has a different meaning in Javascript and in PHP: In Javascript it is used for property accessor while PHP uses it for string concatenation. For property access in PHP you use the -> operator on objects (and the :: operator on classes) instead.

So to get the same behavior you would need to have an object value with such a method instead of a 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;
    }
}

Then you can do this:

$int = new Integer(9);
var_dump($int->between(6, 14));

But maybe it already suffuces if you just name the function properly and switch the parameter order:

isInRange($val, $min, $max)


$int is of the primitive type int and contains the value 9. It is not an object that has instance methods/functions. This (sadly) isn't Ruby ;)

What you want isn't possible in PHP unless you do something like this - but I wouldn't advise it:

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);
    }

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜