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.
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: