PHP variables in function argument is not working - php

I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?

you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>

I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError

Related

Check if method is false then output results

I have a class that contains a method which carries out various database checks. It then returns the value, if exists.
Here is a very basic setup example:
PHP Class
class myClass{
var $aVar1;
var $aVar2;
function myMethod()
{
// database query
// if results from query return **results**
// else return false
}
}
HTML/PHP File
// setup $myClass object var
<?php if($myClass->myMethod(): ?>
// lots of html
<?php echo $myClass->myMethod() ?>
// lots of html
<?php endif; ?>
This occurance happens multiple times throughout my file with different methods. My question is, I am calling the method initially and checking if it's false and then calling it again to echo the output.
I could do the following but would end up with a variable declaration on every method. There must be a more professional approach?
<?php
$myMethod = $myClass->myMethod();
if($myMethod): ?>
// lots of html
<?php echo $myMethod ?>
// lots of html
<?php endif; ?>
Is there a cleaner more efficient way of doing this?
Age old problem. One common technique is to store the return val in a temporary variable
$result=$myClass->myMethod();
if($result!=FALSE)
echo $result;
You can also use a simpler version
if($result=$myClass->myMethod())
echo $result;
And you can also use the simplest one!
echo $myClass->myMethod() ?: '';
Simpler than the simplest one!
echo $result=$myClass->myMethod();
You can do this to reduce verbosity:
<?php
function foo($bool = true) {
$result = array();
if($bool) {
$result = array('bar');
}
return $result;
}
if(! array()) {
echo 'empty array evaluates to false.';
}
if($result = foo()) {
var_export($result); // Will dump array with 'bar'.
}
if($result = foo(false)) {
var_export($result); // Won't happen.
}
If your return is truish then the contents of the if will execute.

Can't get the set value of varible in one function in other diff func in the same class php

I am having a problem with this variable "admin_user_id".. i want to set the val of the var in one function and use that var value in other function here..
But problem is that it gives null. i think its bcz of diff reference of the class..
class ChangeRequestProcessController extends AppController{
static $admin_user_id;
public function ajax_list_of_change_request(){
$this->autoRender = false;
$params = array();
$params[] = $this->Auth->user('id');
//debug($params);
$result = $this->AppProcess->callProcedure('ListOfChangeRequestProcess', $params);
//echo("here:"+$result);
$admin_user_id=$params[0];
//debug( $this->admin_user_id);
echo json_encode($result);
}
public function application_attachment_upload_with_title() {
$this->autoRender = FALSE;
$attachment_array[]=$this->admin_user_id;///p_admin_user_id
//$attachment_array[]="name";///p_uploaded_by
$attachment_array[]=$_POST['title'];///p_attachment_title
// $attachment_array[] = $loged_on_id;
//$attachment_array[] = $_FILES[0]['name'];
//$attachment_array[] = $_POST['title'];
debug($attachment_array);
$result = $application->AttachmentTemp->callProcedure('ChangeRequestAttachmentFinalAddWithTitle', $attachment_array);///call procedure
echo json_encode($result);///result
}
how to solve this problem in php so that the value persists(i think static var will solve it..but it also gives undefined var error inside function)???
Thanks in advance
(this doesn't fit the comment box, so here i go...)
Assuming
// your code to get this...
$admin_user_id = $params[0];
You can store it in a session using this:
if(!session_id()){
session_start();
}
$_SESSION['admin_user_id'] = $admin_user_id; // again, assuming this is the value!
To read it (in your second call/method), simply do:
if(!session_id()){
session_start();
}
$admin_user_id = $_SESSION['admin_user_id'];
For more info, see the php.net: sessions and $_SESSION

How do I share same variable between independent functions

How do I share same variable between independent functions? I don't want to use globals and at the moment, I'm not using OO. This example only works within nested functions:
$example = function() use ($id){
echo 'id is: ' . $id;
};
Is there a way to access (read: to call) that nested function from a different function? I could then return $id.
Main issue: I'm retrieving an ID from a database and I want the moderator to be able to edit material based on the ID that is being retrieved from the database.
As mentioned in my comment , I'm not 100% what exactly you mean by independent and nested function but here is PHP's manual on (anonymous function)[http://php.net/manual/en/functions.anonymous.php].
Anyway I have put a sample together assuming you are really meaning nested functions
<?php
function wrapperOne($id) {
$newId = function($id) {
return $id * 2;
};
return $newId($id);
}
function wrapperTwo($id) {
$doSomething = function() use(&$id) {
$id *= 3;
};
$doSomething();
return $id;
}
echo wrapperOne(2); // 4;
echo PHP_EOL;
echo wrapperTwo(2); // 6;
You can use passing by reference read this
function changeMyID(&$id)
{
$id = 1;
}
function printMyID($id)
{
echo $id;
}
$id = 2;
changeMyID($id);
printMyID($id); // this will output 1;

PHP SQL Function

Can someone please tell me why my function is not working?
function myappsbdo($sqlquery, $tabname)
{
try
{
$pdo = new PDO("mysql:host=127.0.0.1;port=3306;dbname=myapps","root","");
}
catch (PDOException $e)
{
echo "Problème de connexion";
exit();
}
$sql = $sqlquery;
$result = $pdo->query($sql);
$tabname = $result->fetchALL(PDO::FETCH_NUM);
}
I do a var_dump of the variable I chose for my $tabname and it's an empty array. There is suppose to have my db data in it...
Thanks!
EDIT: this is how I call it.
myappsbdo("SELECT * FROM categorie", $tab1);
The function argument $tabname was passed by value, therefore your subsequent assignment to that variable changes only the value of the function-scoped variable $tabname and not of the calling-scoped variable $tab1.
You want to pass by reference instead:
function myappsbdo($sqlquery, &$tabname) {
// ^---- notice the ampersand character
// etc.
$tabname = $result->fetchALL(PDO::FETCH_NUM);
}
Or, alternatively, return the resultset:
function myappsbdo($sqlquery) {
// etc.
return $result->fetchALL(PDO::FETCH_NUM);
}
$tab1 = myappsbdp('SELECT * FROM categorie');
Note that you probably ought to make your PDO object static, so that the database connection can be reused in successive function calls.

PHP getter method question

Hi Im new to PHP so forgive the basic nature of this question.
I have a class: "CustomerInfo.php" which Im including in another class. Then I am trying to set a variable of CustomerInfo object with the defined setter method and Im trying to echo that variable using the getter method. Problem is the getter is not working. But if I directly access the variable I can echo the value. Im confused....
<?php
class CustomerInfo
{
public $cust_AptNum;
public function _construct()
{
echo"Creating new CustomerInfo instance<br/>";
$this->cust_AptNum = "";
}
public function setAptNum($apt_num)
{
$this->cust_AptNum = $apt_num;
}
public function getAptNum()
{
return $this->cust_AptNum;
}
}
?>
<?php
include ('CustomerInfo.php');
$CustomerInfoObj = new CustomerInfo();
$CustomerInfoObj->setAptNum("22");
//The line below doesn't output anything
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
//This line outputs the value that was set
echo "CustomerAptNo = $CustomerInfoObj->cust_AptNum<br/>";
?>
Try
echo 'CustomerAptNo = ' . $CustomerInfoObj->getAptNum() . '<br/>';
Or you will need to place the method call with in a "Complex (curly) syntax"
echo "CustomerAptNo = {$CustomerInfoObj->getAptNum()} <br/>";
As your calling a method, not a variable with in double quotes.
for concat string and variables, you can use sprintf method for better perfomace of you app
instead of this:
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
do this:
echo sprintf("CustomerAptNo = %s <br />", $CustomerInfoObj->getAptNum());
check http://php.net/sprintf for more details

Categories