douna6802 2014-01-07 07:15
浏览 56
已采纳

使用PHP无法在wordpress插件中显示类变量

I am working on a WordPress plugin and started working with classes to store information such as database settings. I have however run into a problem. I cannot output or echo the variables inside my classes. I created another test plugin just to test certain concepts. This is the plugin code from my test plugin to test classes:

<?php
/* WordPress Plugin */
//  create class
class test
{
    //  Variable
    public $HW = "HELLO WORLD!";

    //  Function to return variable
    public function getHW()
    {
         return $this->HW;
    }

    //  Function to set variable
    public function setHW($newHW)
    {
         $this->HW = $newHW;
    }
}

//  Initiate class
$classObj = new test();

//  Output data
function displayClass()
{
    echo "hello world!";
    echo $classObj->getHW();
}

//  Add code to display in wordpress
add_shortcode('test_hw', 'displayClass');
?>

I know that the wordpress section works because 'hello world!' displays on the page. However I cannot get the variables inside the class to load. It either prevents the page from loading or it doesn't display the variable. I cannot seem to find the error. Any help would be appreciated.

I have even tried code like this:

$classObj = new test();
$testHW = $classObj->getHW();

and

$classObj = new test();
$testHW = $classObj->HW;

Neither of these options work either. I am running Apache 2.4.6 with PHP 5.5.7 on Fedora 19.

  • 写回答

1条回答 默认 最新

  • donglou8371 2014-01-17 13:41
    关注

    I don't think $classObj is available in the function, because it is instantiated outside it. You could try making $classObj global. It is not a recommended solution, but it seems to be a normal solution in WordPress. Try this code:

    <?php
    /* WordPress Plugin */
    //  create class
    class test
    {
        //  Variable
        public $HW = "HELLO WORLD!";
    
        //  Function to return variable
        public function getHW()
        {
             return $this->HW;
        }
    
        //  Function to set variable
        public function setHW($newHW)
        {
             $this->HW = $newHW;
        }
    }
    
    //  Initiate class
    global $classObj;
    $classObj = new test();
    
    //  Output data
    function displayClass()
    {
        global $classObj;
        echo "hello world!";
        echo $classObj->getHW();
    }
    
    displayClass();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀