PHP - GETH - Cannot return variable inside function

461 Views Asked by At

So I am calling a function to get the balance of an ethereum account.

I am using the php web 3 found here.

I wrapped the web3 class inside my own function.

So I call my function -> my function executes the web3 eth command.

My function that calls the eth command:

    public function getAccountBalance($account) {

        $newBalance = '';

        $this->web3->eth->getBalance($account, function ($err, $balance) use($newBalance) {

            if ($err !== null) {
                echo 'Error: ' . $err->getMessage();
                return;
            }

            $newBalance = $balance->toString();
            echo $newBalance; // this echos the balance fine

        });
        echo $newBalance; // this returns empty, as like we defined at the top
        return $newBalance;
    }

I am trying to return the balance from the eth function to return it within my getAccountBalance() function but whenever I try to return it, it gives empty, as if it didn't update the $newBalance value inside the $this->web3->eth->getBalance($account, function ($err, $balance) use($newBalance) { callback.

If I echo it inside the $this->web3->eth->getBalance($account, function ($err, $balance) use($newBalance) { callback, it outputs the correct balance fine.

If I try and echo it outside of the $this->web3->eth->getBalance($account, function ($err, $balance) use($newBalance) {, it gives me the value at the top of my function, where I define it: $newBalance = '';, so it's giving me an empty response.

I am not sure why this command does not let me and some others do...

I have tried adding global $newBalance instead of use($newBalance) too but still no luck.

1

There are 1 best solutions below

0
On

Okay, so that was quick. It turns out my code is completely fine, except from 1 & i missed out.

I need to use:

$this->web3->eth->getBalance($account, function ($err, $balance) use(&$newBalance) {

Without this &, it could not pull the variable into the function. With this added, It now returns the balance as I wish.