【问题标题】:How can I call a method into a function of another method?如何将一个方法调用到另一个方法的函数中?
【发布时间】:2017-07-11 06:33:17
【问题描述】:

Here 是我的代码:

class myclass{

    public function one(){
        return 'sth';
    }

    public function two(){
        function myfunc($arg){
            if ($arg){
                return $this->one();
            } else {
                return 'nothing';
            }
            myfunc(true);
        }
    }
}

$obj = new myclass;
echo $obj->$this->two();

正如您在小提琴中看到的那样,它会引发此错误:

致命错误:未捕获的错误:在 /in/E1U9n:25 中不在对象上下文中时使用 $this

我该如何解决这个问题?预期结果是sth

【问题讨论】:

  • 反对者,请发表评论并解释我的问题有什么问题?
  • 如果你改变 echo $obj->$this->two(); 会发生什么到echo $obj->two();
  • @PavelJanicek 在您的情况下,错误将消失3v4l.org/bhSiL。但是为什么sth不会被打印出来呢?
  • 老实说不知道。据我所知,它应该返回一些东西......
  • 另外,我强烈建议将此问题编辑为较新的问题,因为可以通过删除一个拼写错误来“解决”这个问题

标签: php function methods


【解决方案1】:
  1. 首先调用 myfunc(true);在它自己的范围内。所以它不是 据我所知,可以在其范围内调用函数
  2. 其次,您在不知道它属于哪个类的函数范围内调用 $this。
  3. 第三,你没有从你的函数 two() 中返回任何东西,就像它假设的那样。它不会回显任何内容。
  4. 见小提琴https://3v4l.org/sl4eq

    class myclass{
    
        public function one(){
            return 'sth';
        }
    
        public function two(){
            function myfunc($arg){
                if ($arg){
                    $newobj = new myclass();
                    return $newobj->one();
                } else {
                    return 'nothing';
                }
    
            }
            return myfunc(TRUE);
        }
    }
    
    
    $obj = new myclass;
    echo $obj->two();
    

【讨论】:

  • 是的。我刚发现也是一样。太棒了!投我一票
  • 好一个@MartinAJ
【解决方案2】:

你的代码真的很乱,因为你缺乏基础知识和经验。我强烈建议您阅读有关 PHP 中 OOP 的基础知识。 http://php.net/manual/en/language.oop5.php

<?php

class myclass {

    public function one()
    {
        return 'sth';
    }

    public function two()
    {
        return $this->myfunc(true);
    }

    protected function myfunc($arg)
    {
        if ($arg)
            return $this->one();
        else
            return 'nothing';
    }

}

$obj = new myclass;
echo $obj->two();

【讨论】:

    猜你喜欢
    • 2015-06-16
    • 2015-01-03
    • 2010-12-24
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    相关资源
    最近更新 更多