I can't access to global variables

I'm trying get access to variables - globals:

The next code work for me:

$a = 1;
$b = 2;
function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'] ;
}
Sum();
echo $b;

and this not work:

$a = 1;
$b = range(1, 500);
function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'] ;
}
Sum();
echo $b;

What's the problem?

note: I don't want to use: global $a; global $b;

Upvotes: 0

Views: 91

Answers (2)

Charaf JRA
Charaf JRA

Reputation: 8334

It's because you are trying to do SUM of array and number : this is working :

<?php
$a = 1;
$b = range(1, 500);

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'][0] ;//0 or any index
}
Sum();
echo $b;
?>

If you want to add $a to sum of array $b then use array_sum() like this :

   function Sum()
    {
        $GLOBALS['b'] = $GLOBALS['a'] + array_sum($GLOBALS['b']) ; 
    }

Upvotes: 3

Dave Walker
Dave Walker

Reputation: 122

In your second example you are using php "range": http://php.net/manual/en/function.range.php

which will return an array then you are attempting an addition within your Sum function.

ERROR = Types do not match in the second function!

Upvotes: 1

Related Questions