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.
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.
Related
I am trying to use a php function to get the prices of a tola (11.664 grams) at an order status page. The function uses a php page 'priceApi4CurCtrl.php' that fetches the price data from a website using an external API. My function is as follows:
function tolaPrice($cur_pick) {
require('priceApi4CurCtrl.php');
if($cur_pick == 'pkr') {
$tola_price = $bitprice_pkr*10*11.664;
return $tola_price;
} elseif($cur_pick == 'usd') {
$tola_price = $bitprice_usd*10*11.64;
return $tola_price;
} elseif($cur_pick == 'aed') {
$tola_price = $bitprice_aed*10*11.64;
return $tola_price;
}
}
// Succeeds for the first call as under
$cur_pick = 'pkr';
echo tolaPrice($cur_pick);
// Fails for the second call as under
$cur_pick = 'aed';
echo tolaPrice($cur_pick);
The function works fine for the first call using echo tolaPrice($cur_pick). However, it fails all subsequent calls and hence I am unable to complete the order status of second and subsequent orders.
I am not sure how to work around this.
Instead of trying to wrap an if else loop in a function, I simply calculated the prices in a separate file named tola_price.php as follows:
include('priceApi4CurCtrl.php');
$tola_price_pkr = $bitprice_pkr*10*11.664;
$tola_price_usd = $bitprice_usd*10*11.64;
$tola_price_aed = $bitprice_aed*10*11.64;
And then called the tola_price.php within my script with if else loop as follows:
require_one('tola_price.php');
if($cur_pick == 'pkr') {
$tola_price = $tola_price_pkr;
} elseif($cur_pick == 'usd') {
$tola_price = $tola_price_usd;
} elseif($cur_pick == 'aed') {
$tola_price = $tola_price_aed;
}
And then used the prices to build further script.
Thanks to those who offered help
I have this code:
public function taxesData(Product $product)
{
$taxes = \Auth::user()->taxes;
foreach ($taxes as $tax) {
echo "$product->getTax($tax)";
}
}
which on testing gives this error:
Type error: Too few arguments to function App\Product::getTax(), 0 passed in E:\projects\ims\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php on line 411 and exactly 1 expected
However, just a small change makes it works, but I am not able to understand. Why?
public function taxesData(Product $product)
{
$taxes = \Auth::user()->taxes;
foreach ($taxes as $tax) {
echo $product->getTax($tax);
}
}
Please help.
I tried to simplify it for the purpose of posting here... actually i am creating json with html component for a datatable ->
public function taxesData(Product $product)
{
$taxes = \Auth::user()->taxes;
return datatables()
->of($taxes)
->addColumn('check',function($tax) use($product){
if($product->hasTax($tax)){
return "<input type='checkbox' class='input-sm row-checkbox' name='tax[$tax->id]' value='$tax->id' checked>";
}else{
return "<input type='checkbox' class='input-sm row-checkbox' name='tax[$tax->id]' value='$tax->id'>";
}
})
->editColumn('tax', function($tax) use($product){
return "<span class='currencyinput form-control'>
<input id='rate' type='text' name='rate' value='$product->getTax($tax)' required autofocus>
</span>"
})
->toJson();
}
Adding getTax method
public function getTax(Tax $t)
{
if($this->hasTax($t)){
return $this->taxes->find($t->id)->pivot->tax;
}
else{
return $t->pivot->tax;
}
}
public function hasTax(Tax $tax)
{
foreach ($this->taxes as $t) {
if($t->id == $tax->id){
return true;
}
}
return false;
}
It fails because you are not following the correct syntax of echo strings.
This would work:
echo "{$product->getTax($tax)}";
or actually, because you dont' need the quotes for such a simple expression:
echo $product->getTax($tax);
Here's what I've done so far.
Just for simplicity, I've created a sample Model.
// SampleModel.php
public function relatedModels()
{
return $this->hasMany(RelatedModel::class);
}
// this is like an accessor, but since our model doesn't have
// a property called `relatedModels`, Laravel will ignore it
// until later...
public function getRelatedModels()
{
return "Sample";
}
Given the following code, here are the outputs.
$a = SampleModel::find($id);
$a->relatedModels;
// this returns a collection of related models to this model.
$a->getRelatedModels();
// this returns "Sample";
// HOWEVER, when we try to interpolate that member function call.
"$a->getRelatedModels()"
// this throws error that the method `getRelatedModels` must return a relationship.
// I've also tried to add an argument to my existing function to be in-line with your situation.
public function getRelatedModels($a) ...
// this works well
$a->getRelatedModels(1);
// but this, yes, it throws the error as same as what you've got.
"$a->getRelatedModels(1)";
The error pointed out this line in the framework's codebase.
// HasAttributes.php
protected function getRelationshipFromMethod($method)
{
$relation = $this->$method(); // <-- this line
For some reason, doing "$a->getRelatedModels(1)" triggers the __get magic method of the model.
Which branches down to this stack call.
// Model.php
public function __get($key)
{
return $this->getAttribute($key);
}
// |
// V
// HasAttributes.php
public function getAttribute($key)
{
...
return $this->getRelationValue($key);
}
// |
// V
// HasAttributes.php
public function getRelationValue($key)
{
...
if (method_exists($this, $key)) {
return $this->getRelationshipFromMethod($key);
}
}
// |
// V
// HasAttributes.php
protected function getRelationshipFromMethod($method)
{
$relation = $this->$method(); // <-- lastly to this
// $method = "getRelatedModels"
// since our method `getRelatedModels` needs an argument
// this call will fail since it wasn't able to provide an argument.
...
}
That's why you're getting the too few arguments passed exception. I want to investigate further but I have to go home!
I don't know if this is a legit bug for Laravel, but if you do think so, issue it on Laravel's github repository.
UPDATE
I've posted an issue in github and this is one of the comments which truly made sense for me.
This is neither a issue with Laravel, nor with PHP. You are just using the wrong syntax, see it here: https://github.com/laravel/framework/issues/23639
Github user #staudenmeir commented:
"$sampleModel->getRelatedModels()" is equivalent to "$sampleModel->getRelatedModels"."()".
The usage of variables in strings is limited to "$foo" and "$foo->bar". Function calls like "$foo->bar()"
don't work. You can (but shouldn't) use curly braces for that: "{$foo->bar()}"
The better solution is just simple string concatenation:
"text..." . $sampleModel->getRelatedModels() . "more text..."
So that is why the magic method __get is being called.
I have one function call remove_certificate_packages($certificate_id, array_keys($package_id)) this will invoke the below function
function remove_certificate_packages($certificate_id, $package_id)
{
if (is_numeric($package_id)) // so this is list of package id:s
$package_id = array($package_id);
if (!$package_id) return true;
**notify_package_unlinked($certificate_id,array_keys($package_id));**//one more func call
return true;
}
in this function, I have one more function call "notify_package_unlinked" I need to pass the "$package_id". It will call the appropriate function but the problem is, in the "notify_package_unlinked" function the value is showing "Array". What is the problem? Could you please help
function notify_package_unlinked($certificate_id,$package_id)
{
$query="select id,filename,version from packages where id =$package_id";
$res = db_query($query);
$package= db_fetch_object($res);
$packid=$package->id;
$packname=$package->filename;
$packversion=$package->version;
print "$packid"; // here it is printing the value"Array"
}
I got my output using foreach loop .
foreach($package_id as $id){$pack=$id;}
i have 2 functions in a controller,
function feed()
{
$xml = simplexml_load_file('http://localhost/feed.php');
// pass to other function
$this->purchased($xml->prices);
foreach ($xml->prices as $price) {
echo ' <tr id="'.$price->sign.'"><td class="price">'.$price->wholesale.'</td>';
}
}
in the above function i take some values from a feed and append it to a html in the front end using jquery
in the below function what i do is list down all the products purchased by a particular user. this function also refreshed every 5 seconds.
function purchased($price)
{
foreach ($price as $x)
{
$retail = $x->retail;
}
}
what i need to do is get the values returned form the function feed() to the purchased function to do some calculations .. but when i use the above method i get the bellow error
Message: Undefined variable: price
Message: Missing argument 1 for Actions::purchased()
can someone tell me how can i get the prices from the feed function and use it with the purchased function?
Not sure if I understood what are you doing and what are you trying to achieve, but..
Passing variables works only when you call function. So, when you execute feed() function, then you call purchased() function and pass variable. purchased() works, ends, and then script goes back to the feed() function.
Calling purchased() from anywhere else doesn't give you the values from feed() function.
Try to change function to:
function purchased($price = '')
{
if (!isset ($price) || empty($price)) {
$xml = simplexml_load_file('http://localhost/feed.php');
$price = $xml->prices;
}
foreach ($price as $x) {
$retail = $x->retail;
}
}
Basically, I have two functions as shown below, the first function checks if the pickup is an airport address (which is being sent via ajax from jquery function). If it is an airport basically I want to send the variable $fare from getAirportFare function to getFinalFare function, so that it adds a charge if it is an airport address. I was just wondering how I would do this? (still trying to learn PHP)
Any help would be much appreciated.
//DEBUG//
public function getAirportFare($fare, $fieldAirport) {
if ($fieldAirport == 'airport') {
$fare = $fare + 50.00;
return $fare;
}
}
//END OF DEBUG//
private static function getFinalFare($fare) {
$final_fare = ($fare * self::$fare_factor);
if (self::$str_wait_return == "true") {
$final_fare = $final_fare * 2;
}
if (self::$str_return == "true" && self::$return_date != "false" && self::$return_time != "false") {
// We need to calc to fare based on the return date and time
$return_fare = self::getFare(1);
// Append to final fare
$final_fare = $final_fare + $return_fare;
}
// Create new journey object with the info that we have so far
/*$journey = new Journey($journey_id,$pickup,$dropoff,$vias,$distance,$vehicle,
$date_time,$return_journey,$meet_greet,$extras);*/
return number_format($final_fare,2);
}
To send a variable from one function to another (or from an instance method to a static method, as you're doing here), call the second function within the first function, and pass it the variable as an argument, like so:
public function getAirportFare($fare, $fieldAirport) {
if ($fieldAirport == 'airport') {
$fare = $fare + 50.00;
return self::getFinalFare($fare);
}
}
Your instance method will now return the return value of your static method.
If I understand this correctly, it's as simple as this:
//DEBUG//
public function getAirportFare($fare, $fieldAirport) {
if ($fieldAirport == 'airport') {
$fare = $fare + 50.00;
// Send the fare to the getFinalFare function and assign it's result.
$final_fare = self::getFinalFare($fare);
return $final_fare;
}
}
Let me know if I haven't answered your question.
I believe you must declare global $fare outside the function, and when use inside it, use $this->fare.