【问题标题】:php call another function in a function [duplicate]php在函数中调用另一个函数[重复]
【发布时间】:2014-04-23 15:05:44
【问题描述】:

我试图在另一个函数中调用一个函数。根据他们所说的使用

的一些研究

$this->

应该可以。但它给了我

致命错误:不在对象上下文中使用 $this

function addstring($input, $addition_string , $position) {
    $output = substr_replace($input, $addition_string, $position, 0);
    return $output;
}


function test($astring) {
    $output2 = $this->addstring($astring, 'asd', 1);
}

查看我的其余代码:

http://pastebin.com/5ukmpYVB

错误:

致命错误:在第 48 行的 BLA.php 中不在对象上下文中时使用 $this

【问题讨论】:

  • “查看我的其余代码” --- 你有足够的代表点来发布它。
  • 删除$this->
  • 或者更好的是,添加一个类。
  • $this-> 表示当前类

标签: php function


【解决方案1】:

$this-> 如果你在一个类中是需要的,如果你不是,只需通过它的名字来调用函数:

function test($astring) {
    $output2 = addstring($astring, 'asd', 1);
}

【讨论】:

    【解决方案2】:

    除了尼古拉斯提到的错误,

    function test($astring) {
    

    没有返回值,也没有通过引用使用参数,这意味着该函数没有做任何事情,只是在浪费性能。

    演示如何将函数引入class context

    class StringHelper
    {
        private $output;
    
        protected function addstring($input, $addition_string , $position) {
            $output = substr_replace($input, $addition_string, $position, 0);
            return $output;
        }
    
        public function test($astring) {
            $this->output = $this->addstring($astring, 'asd', 1);
            return $this;
        }
    
        public function getOutput() {
            return $this->output;
        }
    }
    
    
    $stringObj = new StringHelper;
    echo $stringObj->test('my string')->getOutput();
    

    【讨论】:

      猜你喜欢
      • 2017-03-07
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      相关资源
      最近更新 更多