PHP / Laravel:复制对象和更改值的深度

It is possible to clone an instantiated object and change some value and create a new object with these changed values but without changing the values of the original object.

I know I can perform a deep copy using the command unserialize(serialize($swift)), but I have not found any way to change the values.

Source/Original:

Swift_Mailer {#777
  -transport: Swift_SmtpTransport {#779
    -handlers: array:1 [
      "AUTH" => Swift_Transport_Esmtp_AuthHandler {#783
        -authenticators: array:5 [
          0 => Swift_Transport_Esmtp_Auth_CramMd5Authenticator {#784}
          1 => Swift_Transport_Esmtp_Auth_LoginAuthenticator {#785}
          2 => Swift_Transport_Esmtp_Auth_PlainAuthenticator {#786}
          3 => Swift_Transport_Esmtp_Auth_NTLMAuthenticator {#787}
          4 => Swift_Transport_Esmtp_Auth_XOAuth2Authenticator {#788}
        ]
        -username: "myname@domain.local"
        -password: "mypassword"
        -auth_mode: null
        -esmtpParams: []
      }
    ]
    -capabilities: []
    -params: array:8 [
      "protocol" => "ssl"
      "host" => "mail.domain.com"
      "port" => 465
      "timeout" => 30
      "blocking" => 1
      "tls" => false
      "type" => 1
      "stream_context_options" => []
    ]

Changed:

Swift_Mailer {#777
  -transport: ...
        ]
        -username: "myname@otherdomain.local"
        -password: "otherpassword"
        ...
      }
    ]
    -capabilities: []
    -params: array:8 [
      "protocol" => "tls"
      "host" => "mail.otherdomain.net"
      "port" => 888
      ...
    ]

1个回答



不确定您正在运行哪个PHP版本,但克隆浮现在脑海中。
请注意,对象中的对象等可能是一个问题,具体取决于 __ clone </ code是否/如何 >为对象设置了功能。</ p>
</ div>

展开原文

原文

Not sure which PHP version you are running, but clone comes to mind. Note that objects within the objects etc might be an issue depending on if/how the __clone function is setup for the object.

dqnhfbc3738
dqnhfbc3738 对于更改私有属性必须使用任何魔术与PHP反射。 但首先想想为什么真的需要这样做而不是用新属性创建新对象。 另外使用像@inquam这样的setter说是最好的选择。
一年多之前 回复
douyan6871
douyan6871 您只需在新对象上调用可用的setter方法即可。 如果你想改变非公开可用的成员变量,你将不得不做一些“魔术”。 但通常情况下,对象旨在让您访问预期必须访问的内容。
一年多之前 回复
dongshuming7131
dongshuming7131 谢谢....但是如何更改克隆对象的值?
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐