首页 > 解决方案 > PHP:在类中调用具有返回值的函数

问题描述

当我这样做时:

class MyClass
{
    public function func1()
    {
        $temp = $this->func2();
        return $temp;
    }
    function func2()
    {
        return "bla2";
    }
}

该网站保持空白,似乎 PHP 因错误而崩溃(不过,error.log 中没有条目)

但是当我这样做时:

class MyClass
{
    public function func1()
    {
        $temp = "bla1"; //$this->func2();
        return $temp;
    }
    function func2()
    {
        return "bla2";
    }
}

有用; “bla1”正在返回。显然我以错误的方式调用 func2 。它是如何正确的?

用我的 php-script 的这段摘录扩展我的原始帖子。我实际上已经将原始代码剥离并尝试了它 - >它仍然会导致错误。值得一提的是,它是 wordpress 的插件。如果没有函数调用,它确实可以工作并返回由 wordpress 显示的文本。

<?php
    add_shortcode("pd",array("pdCategories","ShortcodeParse_c"));
    $pd = new pdCategories();

    class pdCategories
    {
        public function ShortcodeParse_c($atts)
        {
            $temp = "";
            $temp.= "test<br>"; //this works
            $temp.= $atts["category"]; //this also works
            $temp.= $this->ShowCategories_c($atts["category"]); //this causes an error
            return $temp;
        }
        
        private function ShowCategories_c($kats)
        {
            $temp = "starting...<br>"; //init
            return $temp;
        }
    }
?>

标签: phpfunctionclassreturn-value

解决方案


推荐阅读