【问题标题】:PHP Chaining methodsPHP 链接方法
【发布时间】:2013-03-06 07:58:59
【问题描述】:
class AAA

{

    function getRealValue($var)
    {
        $this->var = $var;
        return $this;
    }

    function asString()
    {
        return (string) $this->var;
    }

}

$a = new AAA;
$a->getRealValue(30); 
$a->getRealValue(30)->asString(); 

所以当我调用 $a->getRealValue(30) 它应该返回 30,

但是当我调用 $a->getRealValue(30)->asString() 它应该返回 '30' 作为字符串'。

谢谢

【问题讨论】:

    标签: php methods chaining


    【解决方案1】:

    所以当我调用 $a->getRealValue(30) 时它应该返回 30,但是当我调用 $a->getRealValue(30)->asString() 时它应该返回 '30' 作为字符串'。

    这是不可能的 (yet)。当getRealValue 返回一个标量值时,你不能在它上面调用方法。

    除此之外,你的课程对我来说毫无意义。您的方法称为getRealValue,但它接受一个参数并设置该值。所以应该叫setRealValue。抛开方法链不谈,你是不是在寻找一个 ValueObject?

    class Numeric
    {
        private $value;
    
        public function __construct($numericValue)
        {
            if (false === is_numeric($numericValue)) {
                throw new InvalidArgumentException('Value must be numeric');
            }
            $this->value = $numericValue;
        }
    
        public function getValue()
        {
            return $this->value;
        }
    
        public function __toString()
        {
            return (string) $this->getValue();
        }
    }
    
    $fortyTwo = new Numeric(42);
    $integer = $fortyTwo->getValue(); // 42
    echo $fortyTwo; // "42"
    

    【讨论】:

    • 其实他的getRealValue返回this,就是一个对象。问题不在于 ->asString() 调用,它有效。问题在于 getRealValue() 不返回 int 而是返回对象。
    • @HugoDelsing 我最初的陈述不是指他的实际代码,而是引用的段落。
    • 是的,谢谢。例如,我想从某个数组中获取一些值,但之后我想将类型更改为字符串或其他类型。
    • @user2086527 通常很少需要这样做,因为 PHP 无论如何都会以上下文敏感的方式对您的代码进行类型处理。也就是说,如果您在字符串上下文中使用整数,PHP 会计算出来,而无需您显式转换字符串。
    • 是的,但这只是向您展示一个示例。还有其他类似的方法:所以这是不可能的:$a->get('username'); // return 'john' $a->get('username')->getHash(); // 返回 'y692mrth..' ???
    【解决方案2】:

    这不是真的,$a->getRealValue(30) 将返回对象 $a 而不是值。但是 asString 会以字符串格式返回值。

    通常当你想得到这样的东西时,你会这样做:

    $a->getRealValue(30)->get();
    //Or
    $a->getRealValue(30)->getAsString();
    

    【讨论】:

    • 基本上我想从某个数组中获取一些值,但我想将值更改为例如字符串。 // 这将为我获取 id $a->get('id') 所以更漂亮的代码将是这样的: $a->get('id')->asString(); // 它很酷,首先我得到了 id,然后转换它可以理解!!!这是不可能的,那么最好的解决方案是什么: $a->afterConvert('string')->get('id');这会起作用,但它在语义上并不好。这不是那么容易理解。有什么建议吗?
    猜你喜欢
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2012-03-11
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多