PHP   发布时间:2022-04-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了php – 在array_walk中没有对象上下文错误时使用$this大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在类中使用带有闭包的array_walk时遇到了一个奇怪的问题.在我的开发环境中使用php版本5.4.7不会出现这个问题,但它在我的部署环境5.3.3中会出现.

以下代码在我的生产框上运行正常,但在我的部署环境中崩溃:

<?php
    error_reporTing(-1);

    Class TestArrayWalk
    {
        /** @var null|array */
        protected $userInput = null;

        /**
         * This expects to be passed an array of the users input from
         * the input fields.
         *
         * @param  array $input
         * @return void
         */
        public function setUserInput( array $input )
        {
            $this->userInput = $input;

            // Lets explode the users input and format it in a way that this class
            // will use for marking
            array_walk( $this->userInput,function( &$rawValue )
                {
                    $rawValue = array(
                        'raw' => $rawValue,'words' => $this->spliTintoKeywordArray( $rawValue ),'marked' => false,'matched' => array()
                    );
                }
            );
        }

        public function getUserInput()
        {
            return $this->userInput;
        }

        protected function spliTintoKeywordArray( $input )
        {
            if ( ! is_String( $input )){ return array(); }
            return preg_split('/(\s|[\.,\/:;!?])/',$input,-1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        }

    }


    $testArrayWalk = new TestArrayWalk();
    $testArrayWalk->setUserInput(
            array(
                'This is a test input','This is another test input'
                )
        );

    var_dump( $testArrayWalk->getUserInput() );

我得到的错误是:当不在第26行的对象上下文中时使用$this,这是该测试类中$this的唯一用法.我假设在我使用的版本之间发生了一些变化,这使我的开发环境中的代码成为可能.

我还假设,因为我无法更改部署环境(它的客户端,他们不会改变它),我将不得不使用foreach而不是array_walk.

我的问题是:鉴于上述情况,这是否可能在5.3.3中使用array_walk,如果不是我如何使用foreach的方式与使用array_walk相同(更具体地说是& $rawValue位)?

我的环境是:

>我的开发环境是php版本5.4.7
>我的服务器(部署)环境是php 5.3.3版

谢谢.

编辑2

感谢所有帮助过的人.在你的帮助下,我得到了这个工作,并将我的工作代码发布到https://gist.github.com/carbontwelve/6727555以供将来参.

解决方法

这在php手册中有描述:
Version Description
5.4.0   $this can be used in anonymous functions.

Anonymous functions

可能的解决方法是将其重新分配给另一个变量并通过use传递它:

$_this = $this;
function() use($_this) { ... }

但请记住,您将无法访问私人和受保护的成员,因此您必须公开spliTintoKeywordArray

大佬总结

以上是大佬教程为你收集整理的php – 在array_walk中没有对象上下文错误时使用$this全部内容,希望文章能够帮你解决php – 在array_walk中没有对象上下文错误时使用$this所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。