Question

I want to get value in array format with various keys for the method.

Class File

<?php
class Hooks
{

    private $version = '1.4';
    public $hook = array();


    public function __construct(){ }


    public function get_item_hook()
    {
        //bla bla bla
        $this->hook['foo']  = 'resulting data for foo';
        $this->hook['foo1'] = 'resulting data for foo1';
        $this->hook['foo2'] = 'resulting data for foo2';

        return $this->hook;
    }

    public function get_item2_hook()
    {
        //bla bla bla
        $this->hook['another']  = 'resulting data for another';
        $this->hook['another1'] = 'resulting data for another1';
        $this->hook['another2'] = 'resulting data for another2';

        return $this->hook;
    }


}
?>

Code FIle

<?php
// this is in another file

include ('path to above class file');

$hook = new Hooks;
$hook->get_item_hook();

//now how can I get value of $this->hook array()???

$hook->get_item2_hook();

//now how can I get value of $this->hook array()???
?>
Was it helpful?

Solution

You aren't capturing the return value when you call the methods.

Try

$myArray = $hook->get_item_hook();
// ^^ here we store the return value

print_r($myArray);
echo $myArray['foo']; // resulting data for foo

Also as bountyh points out, you missed the function keyword in your methods:

public function get_item_hook()
{
    ...
}

If you turn on PHP errors or check your error log, you should be seeing this error:

Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE ...

To turn errors on:

error_reporting(E_ALL);
ini_set('display_errors', '1');

OTHER TIPS

Just assign the return values to a variable:

$item = $hook->get_item_hook();
print_r($item);
$item2 = $hook->get_item2_hook();
print_r($item2);

you haven't defined the "functions in your class files as functions"

for example is public function get_item2_hook() not public get_item2_hook()

Assign the array to a variable?

$array = $hook->get_item_hook();
print_r($array);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top