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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题