草庐IT

php - 对象通过引用传递。 call_user_func 的参数不是。是什么赋予了?

coder 2024-04-30 原文

在 PHP 中,objects are effectively passed by reference (引擎盖下发生的事情是 a bit more complicated )。同时,call_user_func() 的参数通过引用传递。

那么像这样的一段代码会发生什么?

class Example {
    function RunEvent($event) {
        if (isset($this->events[$event])) {
            foreach ($this->events[$event] as $k => $v) {
                //call_user_func($v, &$this);
                // The above line is working code on PHP 5.3.3, but
                // throws a parse error on PHP 5.5.3.
                call_user_func($v, $this);
            }
        }
    }
}

$e = new Example;
$e->events['example'][] = 'with_ref';
$e->events['example'][] = 'without_ref';
$e->RunEvent('example');
function with_ref(&$e) {
    $e->with_ref = true;
}
function without_ref($e) {
    $e->without_ref = true;
}

header('Content-Type: text/plain');
print_r($e);

输出:

Example Object
(
    [events] => Array
        (
            [example] => Array
                (
                    [0] => with_ref
                    [1] => without_ref
                )

        )

    [without_ref] => 1
)

注意:在文件顶部添加 error_reporting(E_ALL);error_reporting(-1); 没有区别。我没有看到任何错误或警告,当然命令行上的 php -l 也没有显示任何错误。

我实际上希望它在回调函数中有和没有引用的情况下都能工作。我认为在 call_user_func() 中删除 $this 之前的符号就足以为最新版本的 PHP 修复此问题。显然,带有引用的版本不起作用,但同样它不会抛出任何 linting 错误,因此很难追踪这种情况(在我使用的代码库中可能会多次出现)。

我这里有一个实际问题:有什么方法可以使 with_ref() 函数起作用吗?我只想修改 RunEvent() 代码,而不是每个使用它的函数(其中大部分确实使用引用)。

我也有一个好奇的问题,因为我在这里看到的行为对我来说毫无意义。 相反会更有意义。这里到底发生了什么? 看起来惊人的违反直觉的是,函数调用没有和号可以修改对象,而和号不能

最佳答案

参数传递

主要问题是 - 传递给 call_user_func() 的参数将作为传递 - 因此它们将是实际数据的副本。此行为覆盖了事实,即

objects are passed by reference. Note:

Note that the parameters for call_user_func() are not passed by reference.

跟踪误差

在这种情况下,您对“默许同意”的说法并不完全正确。在这种情况下,您将看到级别为 E_WARNING 的错误:

Warning: Parameter 1 to with_ref() expected to be a reference, value given in

So - you will be able to figure out that you're mixing reference and values passing

Fixing the issue

Fortunately, it's not too hard to avoid this problem. Simply create reference to desired value:

class Example {
    function RunEvent($event) {
        if (isset($this->events[$event])) {
            foreach ($this->events[$event] as $k => $v) {

                $obj = &$this;
                call_user_func($v, $obj);
            }
        }
    }
}

-那么结果将完全符合预期:

object(Example)#1 (3) {
  ["events"]=>
  array(1) {
    ["example"]=>
    array(2) {
      [0]=>
      string(8) "with_ref"
      [1]=>
      string(11) "without_ref"
    }
  }
  ["with_ref"]=>
  bool(true)
  ["without_ref"]=>
  bool(true)
}

关于php - 对象通过引用传递。 call_user_func 的参数不是。是什么赋予了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20683779/

有关php - 对象通过引用传递。 call_user_func 的参数不是。是什么赋予了?的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  3. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  4. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  5. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  6. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  7. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  8. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  9. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  10. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

随机推荐