Passing php variables inside function - stripe [duplicate] - php

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed last month.
I am trying pass a value inside stripe function function calculateOrderAmount(array $items): int using variable declared outside function, but its not working. But if I declare variable inside the function function calculateOrderAmount(array $items): int its working. Its confusing.
What is working
function calculateOrderAmount(array $items): int {
// assign session amount to a variable
$amount = 500;
return $amount;
}
What is not working and what I want
$amount = 500;
function calculateOrderAmount(array $items): int {
// assign session amount to a variable
return $amount;
}
I am trying to pass a value to the function from outside, kindly help

If you want your $amount variable to be defined outside the function as a global variable. Then you should tell the function to "import" it like so:
$amount = 500;
function calculateOrderAmount(array $items): int {
global $amount;
// assign session amount to a variable
return $amount;
}
But I wouldn't recommend using global variables. Use a parameter if this value is intended to change, or a constant otherwise.

Related

variable references & in Laravel

In the following code, I noticed &$list is passed by reference in the loop, however $user and $request are passed by variables. Passing $list directly to the loop won't change $list outside the loop scope.
public function index(Request $request, User $user)
{
$list = collect();
$someRelations()->each(function ($val) use (&$list, $request, $user) {
// mutate $list
});
dd($list);
}
Why is this?
Actually its the core PHP functionality rather than Laravel itself, basically when you are passing variables without reference, it actually clone the variable with the same name but in different locations. So, if you make any changes to it, there will be no changes to the value of the variable outside the scope.
Without reference
$x = 10;
(function() use ($x){
$x = $x*$x;
var_dump($x); // 100
})();
var_dump($x); // 10
But, if you pass the value by reference, instead of creating a new variable, it provides the reference to the same original variable. So, any changes made inside the function will change the value of the variable outside scope as well.
Pass by reference
$y = 10;
(function() use (&$y){
$y = $y*$y;
var_dump($y); // 100
})();
var_dump($y); // 100
To know more about it you could visit, https://www.php.net/manual/en/language.references.pass.php

Class-Wide accessible static array, trying to push to it, but keeps coming back empty

class UpcomingEvents {
//Variable I'm trying to make accessible and modify throughout the class methods
private static $postObjArr = array();
private static $postIdArr = array();
private static $pinnedPost;
//My attempt at a get method to solve this issue, it did not
private static function getPostObjArr() {
$postObjArr = static::$postObjArr;
return $postObjArr;
}
private static function sortByDateProp($a, $b) {
$Adate = strtotime(get_field('event_date',$a->ID));
$Bdate = strtotime(get_field('event_date',$b->ID));
if ($Adate == $Bdate) {
return 0;
}
return ($Adate < $Bdate) ? -1 : 1;
}
private static function queryDatesAndSort($args) {
$postQuery = new WP_Query( $args );
if( $postQuery->have_posts() ) {
while( $postQuery->have_posts() ) {
$postQuery->the_post();
//Trying to push to the array, to no avail
array_push(static::getPostObjArr(), get_post());
}
}
//Trying to return the array after pushing to it, comes back empty
return(var_dump(static::getPostObjArr()));
//Trying to sort it
usort(static::getPostObjArr(), array(self,'sortByDateProp'));
foreach (static::getPostObjArr() as $key => $value) {
array_push(static::$postIdArr, $value->ID);
}
}
}
I'm trying to access $postObjArr within the class, and push to it with the queryDatesAndSort(); method. I've tried a couple of things, most recent being to use a get method for the variable. I don't want to make it global as it's bad practice I've heard. I've also tried passing by reference I.E
&static::$postObjArr;
But when it hits the vardump, it spits out an empty array. What would be the solution and best practice here? To allow the class methods to access and modify a single static array variable.
static::$postObjArr[] = get_post()
I didn't think it would of made a difference, but it worked. Can you explain to me why that worked but array.push(); Did not?
Arrays are always copy-on-write in PHP. If you assign an array to another variable, pass it into a function, or return it from a function, it's for all intents and purposes a different, new array. Modifying it does not modify the "original" array. If you want to pass an array around and continue to modify the original array, you'll have to use pass-by-reference everywhere. Meaning you will have to add a & everywhere you assign it to a different variable, pass it into a function, or return it from a function. If you forget your & anywhere, the reference is broken.
Since that's rather annoying to work with, you rarely use references in PHP and you either modify your arrays directly (static::$postObjArr), or you use objects (stdClass or a custom class) instead which can be passed around without breaking reference.

pass argument to filter function in PHP [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
at one point in my function I need to filter an array based on a last digit of a key, but I cannot pass argument to the function I'm using to filter
here's the code:
function functionName($number){
//some code
$items = array_filter(SomeClass::$items, function ($item, $number){
return ($item%10 == $number);
}, ARRAY_FILTER_USE_KEY);
//some code
}
what can I do to make sure the inner function uses $number passed to functionName()?
You can pass variables to closure function by "use"
Eg.
function ($var) use ($yourVarThatYouWannaPass) { return $var;}

Is it possible to Delete a value passed to a method, from within the method

Say I have a method (which in this particular case is a static method), and this method works on a given value. Once completed is there a way that I can automatically in the code, delete the variable (rather than the function copy).
I suspect from all I've read that this is not possible, but there are no clear declarations of such that my searching has found.
An example case:
Static Method:
public static function checkKey($keyValue = null)
{
if(!is_null($keyValue) && !empty($keyValue)) {
if($_SESSION['keyValue'] == $keyValue) {
unset($keyValue,$_SESSION['keyValue']);
return true;
}
unset($keyValue,$_SESSION['keyValue']);
return false;
}
return false;
}
Usage:
$valueToBeChecked = "I want this value unset from within the function"
//PHP page code
AbstractClass::checkKey($valueToBeChecked);
Is there a way that the method checkKey above can delete the value of $valueToBeChecked from within the method checkKey?
The fact it's a static method shouldn't be too critical, it's more the shape of is there a way that the function can delete a value that is set outside the funtion/method, when passed the variable as a parameter?
I realise this is possible if the whole thing is wrapped in a Class and the variable is saved as a class level variable (unset($this->var)), but I'm curious if there's any ability to "reach" variables from outside the scope such as
public static function checkKey($keyValue = null)
{
unset(\$keyValue);
}
I only have limited experience with namespacing but that's my best guess as to if this is possible, how to go about it.
simplified equiviliant outcome:
What I'm trying to reach is this action, entirely within the method:
$valueToBeChecked = "something"
AbstractClass::checkKey($valueToBeChecked);
unset($valueToBeChecked);
You cannot unset a variable from within a function and have that effect propagate. Per the manual:
If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
However, you can get equivalent behavior through pass-by-reference and setting to null:
function kill(&$value) {
$value = null;
}
var_dump($x); // NULL
$x = 'foo';
var_dump($x); // 'foo'
kill($x);
var_dump($x); // NULL
This works because, in PHP, there's no distinction made between a symbol that doesn't exist and a symbol that exists with a NULL value.

How to assign variable php?

I have a following php function:
public function getTrailer()
{
return $this->model->trailer;
}
How to assigned value of $this->model->trailer to $new variable. And can you explain me what $this->model->trailer means, please ?
Thanks !
To assigned the value to a new variable do this:$newVar = $this->model->trailer;
The meaning of $this->model->trailer is that is taking the value that are inside of the structure. Is looking what are inside $this, and inside the model and inside of trailer and taking the value.

Categories