使用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.
我正在使用WordPress插件并开始使用类来存储数据库设置等信息。 然而,我遇到了一个问题。 我无法输出或回显我的类中的变量。 我创建了另一个测试插件来测试某些概念。 这是从我的测试插件到测试类的插件代码: p>
&lt;?php
/ * WordPress插件* /
//创建类
class test
{
//变量
public $ HW =“HELLO WORLD!”;
//返回变量的函数
公共函数getHW()
{
返回$ this-&gt; HW;
}
//设置变量的函数
公共函数setHW($ newHW)
{
$ this-&gt; HW = $ newHW;
}
}
//启动类\ n $ classObj = new test();
//输出数据
function displayClass()
{
echo“hello world!”;
echo $ classObj-&gt; getHW();
} \ n
//添加代码以显示在wordpress
add_shortcode('test_hw','displayClass');
?&gt;
code> pre>
我知道wordpress 部分工作原因是'你好世界!' 显示在页面上。 但是我无法在类中获取要加载的变量。 它要么阻止页面加载,要么不显示变量。 我似乎无法找到错误。 任何帮助将不胜感激。 p>
我甚至尝试过这样的代码: p>
$ classObj = new test();
$ testHW = $ classObj-&gt; getHW();
code> pre>
和 p>
$ classObj = new test() ;
$ testHW = $ classObj-&gt; HW;
code> pre>
这两个选项都不起作用。 我在Fedora 19上使用PHP 5.5.7运行Apache 2.4.6。 p>
div>
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();
?>