PHP Function Argument Default Value - php

Hey all.
I have a processForm function and a displayForm function. If there are missing form fields the processForm function returns an array of missing fields. This is all fine and dandy until I try to include this array into the displayForm function. Here's the problem:
If I don't do this:
displayForm($missingFields=array());
then my validateField function throws a warning that it is expecting the parameter to be an array. However, this overwrites the array returned by the processForm function.
I hope I'm clear. Thanks for any help.
Full Code:
if(isset($_POST['action']) && $_POST['action'] = "login")
{
$messages = processForm();
}
processForm()
if($errorMessages)
{
return array("errors" => $errorMessages, "missing" => $missingFields);
}
else
{
$_SESSION['user'] = $user;
header("Location: index.php");
}
form.php
(!isLoggedIn())? displayForm($messages['errors']=array(),$messages['missing']=array()) : null;
These are the sections of the code I'm having trouble with.
Thanks again.

You don't set default argument values in the call, you set them in the signature, for example
function displayForm($arg1 = array()) {
...
}
When you write
displayForm($messages['errors']=array())
this is actually doing something like this
$messages['error'] = array(); // set $messages['error'] to an empty array
displayForm($messages['error']); // pass an empty array to displayForm
This is because in PHP, the return value from an assignment is the value assigned.

Why are you using this:
displayForm($messages['errors']=array(),$messages['missing']=array())
When you writing "$messages['errors']=array()", this is setting $messeges to blank array. So the parameter is blank. You can just write:
displayForm($messages['errors'],$messages['missing'])

Related

Why is file_put_contents and serialize only adding part of serialize even if the data is coming in?

I am trying to add an object with data in another class and then serializing to a data file. When I look at the data file only 2 characters are added "b:0;", and they are always the same no matter how much I change the object contents and also when I try adding more posts the file stays the same.
I tried changing the object to a normal string and the result was the same (the same two characters "b:0;". I also tried checking if the function was getting the right input.
This is my constructor in the Post class:
function __construct($nam, $mess, $dat){
$this->name = $nam;
$this->message = $mess;
$this->date = $dat;
}
this is my array and function i am using inside guestbook class:
protected $PostList = [];
function addPost($nam, $mes, $dat){
$obj = new Post($nam, $mes, $dat);
array_push($this->PostList, $obj);
// Serialize and save all of the new object array to file
file_put_contents("guestbook/Postdata.txt", serialize($this->PostList));
}
The expected result on the data file was something like this?
a:size:{key definition;value definition;(repeated per element)}
but all i get is "b:0;"
Here is where i use my class on index.php:
<?php
$guestbook = new Guestbook();
if (isset($_REQUEST['addpost'])) {
if (isset($_POST['author']) && isset($_POST['message'])){
if ($_REQUEST['author'] != "" && $_REQUEST['message'] != "") {
$guestbook->addPost($_REQUEST["author"], $_REQUEST["message"], Date('Y-m-d H:i:s'));
}
}
unset($_REQUEST["addpost"]);
header("Location: index.php");
exit();
}
?>
SOLUTION:
file_exists() was always true and by that, I was inserting a bool value in my array. So I solved by using the function filesize("filepath"); instead.
Just a thought, but you setup the __construct($nam, $mess, $dat) but you are passing it to addPost($nam, $mes, $dat). If you are missing the message, either change it to mess or mes, or wouldn't hurt if you had $name, $message, $date just for clarity, but make the change in both
The problem was in the way I was reading the file.
Here is how it looked:
if(file_exists("data.txt")>0){
//$this->PostList = unserialize(file_get_contents("data.txt"));
array_push($this->PostList, unserialize(file_get_contents("data.txt") ) );
var_dump($this->PostList);
}
the file_exists function was always being true since the file existed and the array was loading a false value at first so to solve that i changed to:
if(filesize("data.txt")){
//...
}

PHP function return value disappears (?)

In the following function call the log files show me that
even though before the return call the variable has a value the variable receiving the return value is empty
the if empty has just been included because I didn't believe what is happening.
What am I missing? Any clou?
...
...
$workingProductArray=$this->placeNextItem($workingProductArray, ... );
if (empty($workingProductArray)){
write_log ("DYING array empty");
die(); //<-- and indeed the system dies.
}
}
private function placeNextItem(array $workingProductArray, ... )
{
if ($this->areAllProductsIgnored($workingProductArray)){
print_r($workingProductArray); // <-- SHOWS EXPECTED ARRAY AND VALUES
return $workingProductArray; // returning this value
}
Weird! Try to not print_r2 from placeNextItem function if still doesn't work try to name $workingProductArray to something else for placeNextItem.
I was just digging into the code. and I just noticed I made a terrible thinking mistake...
(which you can't see on the mentioned code... here the code to the function's end)
...
...
$workingProductArray=$this->placeNextItem($workingProductArray, ... );
if (empty($workingProductArray)){
write_log ("DYING array empty");
die(); //<-- and indeed the system dies.
}
}
private function placeNextItem(array $workingProductArray, ... ){
if ($this->areAllProductsIgnored($workingProductArray)){
print_r($workingProductArray); // <-- SHOWS EXPECTED ARRAY AND VALUES
return $workingProductArray; // returning this value
}
...
$this->placeNextItem(array $workingProductArray, ...);
}
So I call this function also from within (recursively), I thought the return statement would go to the method above but instead it goes (doh! off course!) back to it's recursive caller, which is the same method where I have to return the value too...
easy fix:
private function placeNextItem(array $workingProductArray, ... ){
if ($this->areAllProductsIgnored($workingProductArray)){
print_r($workingProductArray); // <-- SHOWS EXPECTED ARRAY AND VALUES
return $workingProductArray; // returning this value
}
...
return $this->placeNextItem(array $workingProductArray, ...);
}

Directly display the value of an array returned by a method

Is it possible to do in one line calling a method that returns an array() and directly get a value of this array ?
For example, instead of :
$response = $var->getResponse()->getResponseInfo();
$http_code = $response['http_code'];
echo $http_code;
Do something like this :
echo $var->getResponse()->getResponseInfo()['http_code'];
This example does not work, I get a syntax error.
If you're using >= PHP 5.4, you can.
Otherwise, you'll need to use a new variable.
What you can do is to pass the directly to your function. Your function should be such that if a variable name is passed to it, it should the value of that variable, else an array with all variables values.
You can do it as:
<?php
// pass your variable to the function getResponseInfo, for which you want the value.
echo $var->getResponse()->getResponseInfo('http_code');
?>
Your function:
<?php
// by default, it returns an array of all variables. If a variable name is passed, it returns just that value.
function getResponseInfo( $var=null ) {
// create your array as usual. let's assume it's $result
/*
$result = array( 'http_code'=>200,'http_status'=>'ok','content_length'=>1589 );
*/
if( isset( $var ) && array_key_exists( $var, $result ) ) {
return $result[ $var ];
} else {
return $result;
}
}
?>
Hope it helps.
Language itself does not support that for an array.
In case you can change what getResponseInfo() return:
You can create simple class, which will have array as an constructor parameter. Then define magical getter which will be just pulling the keys from the instance array
function __get($key)
{
return #content[$key]
}
Then you'll be able to do
echo $var->getResponse()->getResponseInfo()->http_code;
// or
echo $var->getResponse()->getResponseInfo()->$keyWhichIWant;
What i wrote is just proposal. The real __get method should have some check if the exists and so

Call Function Based On Parameter Name

I am passing a parameter, "action", to another file, process.php. The value of "action" will be the name of a function that is defined within process.php. If the function exists, it should be called automatically. I tried the following:
$action = $_REQUEST['action'];
$function = {$action}();
if(function_exists($function))
$function;
else
die('No function.');
That, however, does not work. Any suggestions? Thanks!
As #Positive said you are calling the function on assignment. I just wanted to add a few things - this is a bit risky - what if the request contents were 'phpinfo' or something even more dangerous. Perhaps a better idea would be to select the function from an array of allowed functions:
$allowed_functions = array(
'my_function_one',
'my_function_two'
);
$action = $_REQUEST['action'];
if(in_array($action,$allowed_functions)){
{$action}();
}
else {
die('No function.');
}
Change the assignment to $function like below. Note that function_exists only take the function name.
$action = $_REQUEST['action'];
$function = $action;
Actually you are calling the function with this statment $result = $function();, see Variable functionsPHP-Manual.
and also sanitize the GET parameter according to your function name conventions.

Can I use a function to return a default param in php?

I would like to do something like this:
function readUser($aUser = loadDefaultUser()){
//doing read User
}
I find that it will display a error to me, how can I pass a function return as a default value? Thank you.
I would rather give a Null value for this argument and then call loadDefaultUser() in the body of the function. Something like this:
function readUser($aUser = NULL){
if(is_null($aUser)){
$aUser = loadDefaultUser();
}
//...
}
Yes, you can provide a default argument. However, the default argument "must be a constant expression, not (for example) a variable, a class member or a function call."
You can fake this behaviour by using some constant value for the default, then replacing it with the results of a function call when the function is invoked.
We'll use NULL, since that's a pretty typical "no value" value:
function readUser($aUser = NULL) {
if (is_null($aUser))
$aUser = loadDefaultUser();
// ... your code here
}
You can add a callback-parameter to your loadDefaultUser() function when it's finished it fires the callback function with the return/result. It's a bit like ajax-javascript callbacks.
function loadDefaultUser ( $callback )
{
$result = true;
return $callback($result);
}
function readUser($aUser = NULL){
if ($aUser === NULL){
$aUser = loadDefaultUser();
}
//do your stuff
}

Categories