更改对象 (PHP) 中的受保护值


Change protected value in object (PHP)

当我对数组进行var_dump时$mailer得到:

object(Fooman_EmailAttachments_Model_Core_Email_Template_Mailer)#352 (8) {
["_emailInfos":protected]=>
array(3) {
[0]=>
object(Mage_Core_Model_Email_Info)#409 (11) {
["_bccNames":protected]=>
array(0) {
}
["_bccEmails":protected]=>
array(0) {
}
["_toNames":protected]=>
array(1) {
[0]=>
string(13) "My Name"
}
["_toEmails":protected]=>
array(1) {
[0]=>
string(17) "justatest@test.com"
}
["_data":protected]=>
array(0) {
}
["_hasDataChanges":protected]=>
bool(false)
["_origData":protected]=>
NULL
["_idFieldName":protected]=>
NULL
["_isDeleted":protected]=>
bool(false)
["_oldFieldsMap":protected]=>
array(0) {
}
["_syncFieldsMap":protected]=>
array(0) {
}
}

我想编辑_toEmails,但如何访问和编辑它?

这是一个非常简单的示例(没有错误检查),说明如何使用ReflectionClass执行此操作:

function setProtectedProperty($obj, $property, $value) {
  $reflection = new ReflectionClass($obj);
  $property = $reflection->getProperty($property);
  $property->setAccessible(true);
  return $property->setValue($obj, $value);
}
setProtectedProperty($mailer, '_toEmails', ['foo@bar.com']);

我不必告诉你,这可能是隐藏它的原因,而且很可能有一种方法可以在不直接访问它的情况下设置它(正如其他人确保告诉你的那样),但是你可以扩展类并添加你自己的方法来设置它:

<?php
    class Foo {
        protected $_destroyDatabase = false;
    }
    class Bar extends Foo {
        public function SetDestroyDatabase($destroyDatabase) {
            $this->_destroyDatabase = $destroyDatabase;
        }
    }
    $foo = new Foo();
    $foo->_destroyDatabase = true; //Fatal error
    var_dump($foo);
    /*
        object(Foo)#1 (1) {
          ["_destroyDatabase:protected"]=>
          bool(false)
        }
    */
    $bar = new Bar();
    $bar->SetDestroyDatabase(true); //Success
    var_dump($bar);
    /*
        object(Bar)#2 (1) {
          ["_destroyDatabase:protected"]=>
          bool(true)
        }
    */
?>

演示

阅读类Fooman_EmailAttachments_Model_Core_Email_Template_Mailer的文档。应该有一个你可以调用方法来编辑信息,
$mailer->setEmails('foo').如果没有,则不应修改数据。