1

Arrays created in function test().

Then I would like print their on page test.php.

My code down:

conf.php

function test(){
$str= array(
        'items' => array(
                0 => array(
                        'title' => 'Title',
                        'category' => 'Category name',
                        ),
                1 => array(
                        'title' => 'Title',
                        'category' => 'Category name',
                        ),
        ),
        'details' => array(
                'firstname' => 'firstname',
                'lastname' => 'lastname',
        ),
        'Id' => $Id,
        'OrderId' => 'fsdfsfdsrew'
);


$json = json_encode($str);
$base64 = base64_encode($json);

$sig = signMessage($base64, $secretPhrase);
}

test.php

require_once("conf.php");

test();
print_r($str);
print_r($json);
print_r($base64);
print_r($sig);

Tell me please why code not worked?

Tell me please why weren't printed $str, $json, $base64, and $sig?

How do it?

Preferably without global parameters.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880

2 Answers2

2

You can't without returning them as the function return value. In PHP, variables declared in a function (the arrays you're trying to print_r in this case) are only available within the scope of that function unless you declare them global with the global keyword.

Here's the details on variable scope in PHP: http://php.net/manual/en/language.variables.scope.php

You could construct a larger array to contain these arrays and return them from the test() function:

 function test(){
     //function code here....
     ////...

     $results = array('str'=> $str, 
                      'json'=> $json, 
                      'base64'=>$base64, 
                      'sig' => signMessage($base64, $secretPhrase)
                  ) ;

      return $results;
  }

Then call it like this:

  $results = test();
  print_r($results['str']);
  print_r($results['sjson']);
  print_r($results['base64']);
  print_r($results['sig']);
Ray
  • 40,256
  • 21
  • 101
  • 138
  • i known this, but i would like know how print their if i created `return array('str' =>$str,'json'=>$json','base64'=>$base64,'sig'=>$sig);` –  Jan 17 '13 at 15:52
  • big thanks for my new knowledge) –  Jan 17 '13 at 16:13
0

Many ways to do that: first, you have to return the value if you want use on other class. on your test you can do:

$something = new Conf();
$someelse = $something->test();
echo $someelse;
Guerra
  • 2,792
  • 1
  • 22
  • 32