PHP __toString()魔术方法不返回字符串(解决方案)

时间:2019-04-22 12:43:45

标签: php tostring

我有一个名为FullName的类,并且我使用的是toString()PHP魔术方法,该方法应该返回一个字符串,但我直接收到了Object:

<?php

declare(strict_types=1);

namespace App\Professional\Domain\ValueObjects;

use App\Professional\Domain\Exceptions\NameIsTooShortException;

final class FullName

{
    public $forename;

    public $surname;

    public function __construct(string $forename, string $surname)
    {
        $this->forename = $this->validateAndNormalize($forename);

        $this->surname = $this->validateAndNormalize($surname);
    }

    private function validateAndNormalize($name) : string
    {
        if (strlen($name) === 0) throw new NameIsTooShortException();

        return ucwords($name);
    }

    public function __toString()
    {
        return $this->forename . ' ' . $this->surname;
    }
}

当我尝试这样做时:

$name = new FullName($request->forename, $request->surname);

如果我使用:

回显$ name;

返回的是“ Mike Gen”

但是如果我在数组中添加$ name变量:

$returnValues = array(
    'id' => $professional->id(),
    'name' => $name,
    'message' => 'The professional has been updated'
);

返回不是预期的,我收到此消息:

{“ id”:“ 1”,“名称”:{“姓氏”:“迈克”,“姓氏”:“ Gen”},“消息”:“专业人员已更新”}

已修复,感谢@Nigel Ren,解决方案

$returnValues = array(
    'id' => $professional->id(),
    'name' => (string) $name,
    'message' => 'The professional has been updated'
);

1 个答案:

答案 0 :(得分:0)

当您想要获取对象的字符串表示形式时,可以使用

__toString方法,例如,在调用echo $object隐式 >明确地,将对象强制转换为字符串或将其与另一个字符串连接时。在您的代码中

$name = new FullName($request->forename, $request->surname);

您创建一个新的FullName对象,并将其放入$name变量中。

要查看__toString的工作方式,您需要将对象转换为字符串,例如:

echo $name;
// or
$str = 'The object as string is: ' . $name;
echo $str;

还请注意,var_dumpprint_r 请勿将对象转换为字符串。

这里是simple fiddle

进一步:

{"id":"1","name":{"forename":"Mike","surname":"Gen"},"message":"The professional has been updated"}

json json_encode 不使用强制转换来字符串化。

您要么强制转换为字符串

$returnValues = array(
    'id' => $professional->id(),
    'name' => (string)$name,
    'message' => 'The professional has been updated'
);

或实施JsonSerializable

final class FullName implements JsonSerializable
{
    public function jsonSerialize() 
    {
        return $this->forename . ' ' . $this->surname;
    }

此后,对json的编码将按预期工作,而无需显式转换为字符串-小提琴here