The Overview
I've been experimenting some features which I've learn't using PHP, last night I was working on anonymous functions and for some strange reason when I var_dumped the function it kept returning null.
The Code
Below is the code I've written.
The findOrFail function,
public static function findOrFail($iD, $successCallback = null, $failCallback = null)
{
$db = new Database();
$db->select("users")->fields(["*"])->where(["id" => $iD])->execute("select");
if ($db->rowCount() == 1) {
if (is_callable($successCallback)) {
return $successCallback();
} else {
return true;
}
} else {
if (is_callable($failCallback)) {
return $failCallback($iD);
} else {
return false;
}
}
}
In test.php,
require_once "config.php";
var_dump(User::findOrFail(1, function () {
echo "Found.";
}, function ($iD) {
echo "Failed.";
}));
The Output
The ID 1 exsits so I expect the see when dumping string and the contents to be "Found." however I see this:
Found.NULL
What I have tried?
I looked at another question related to this issue and it said
that it was because of a buggy PHP version (5.3?). So I checked my
PHP version and it is 5.5.8.
I thought maybe because the default parameters ($successCallback and $failCallback) are set to equal null that that may be causing the error to occur. However some quick changes to the code (to remove the null) showed that it didn't fix anything.
So my question is, Why is it showing null? If anyone could shed some light on this issue it would be much appreciated.
Your anonymous functions don't return anything, they just call echo to print something. Use:
return "Found";
and
return "Failed";
Related
I am trying to understand the return keyword and its functionality, however, I am getting a little confused.
I have read this which has been a good starting point, but I can't seem to understand the solution to what I imagine is a very simple problem.
Say I have a PHP file called index.php and I call a function from it like so (imagine it's not being called from within a class or function);
echo $fun -> editAnswer ($obj->answer_id, $obj->answerString ,$obj->correct, $questionID, $lecturer_id);
Then in my function.php I have:
public function editAnswer($answer_id, $answerString, $correct, $questionID, $lecturer_id){
$db = $this -> db;
if (!empty ($answer_id) && !empty ($answerString) && !empty($correct) && !empty($questionID) && !empty ($lecturer_id)){
$result = $db -> editAnswer($answer_id, $answerString, $correct, $questionID, $lecturer_id);
if ($result) {
return "The Updates To Your Answer Have Been Saved!";
} else {
$response["result"] = "failure";
$response["message"] = "The Updates To Your Answer Have Not Been Saved, Please Try Again";
return json_encode($response);
}
} else {
return $this -> getMsgParamNotEmpty();
}
}
If successful, I will return the string The Updates To Your Answer Have Been Saved!, however, this will be immediately echoed to the screen of index.php.
My thinking is that if after calling the function, the user was still on index.php, it might look a little ugly to have a string at the top of the page. Maybe I would want to catch the returned string and then create an alert dialog before displaying it.
How would I go about doing something like that rather than immediately echoing the returned string?
The return value is echoed because you use echo to output the result.
Save the result to a variable and use it later
$result = $fun -> editAnswer ($obj->answer_id, $obj->answerString ,$obj->correct, $questionID, $lecturer_id);
echo "we called the function"
echo "the result was $result"
I am trying to create an instance of a class "announcement".
For example:
$announcement = new announcement;
//code to bind data
$announcement->store();
My store function runs a query to store the information to the database. Everything is working as intended and storing to my database. However when I say:
if($announcement->store())
{
echo 'success';
}
else{
echo 'failure';
}
I get the 'failure' message. Why is my method returning false when it is actually working? Am I missing something with conditional statements and methods?
UPDATE
My store function was not returning anything. So even though it worked it was returning a null value. I return true on query success and now it is working as intended. Thank you.
The store function should return true then your statement will print success message
class announcement {
public function store() {
// after execution code the return value should be like this
return true;
}
}
I created a function to allow me to debug PHP scripts so long as a variable ($debug) is set to 1:
function debug($msg) {
if ($debug == 1) {
echo $msg;
} else {
return false;
}
}
That way, at the top of my script (before the functions.php file is called), I write:
$debug = 1;
to enable debugging, then:
debug("Function executed: " . $data);
at certain points so that I know string values/whatever at that point, with the desired response being the message displayed upon the screen.
However, regardless of what the value of the $debug string is, I never see any echo'd statements.
How can this be achieved?
Debug is not available to your function because it is out of scope. You either:
Need to pass it as a parameter
Use the global keyword to include it in your function (discouraged)
.
function debug($msg, $debug){
if($debug==1){
echo $msg;
} else {
return false;
}
}
or
function debug($msg){
global debug;
if($debug==1){
echo $msg;
} else {
return false;
}
}
It's difficult to say because you provided too few data.
The reason can be that your $debug variable is not known inside a function. Because using globals is not adviced, consider using constants define("DEBUG",1);.
EDIT
I presented within another question how I use a class for doing the same thing as class names are also globally accessed.
The global variable is not accessible to functions until you make it so. Eg:
function debug($msg( {
global $debug;
etc...
PS: Please, don't do this. Find a better way. Really.
$debug is your global variable, so it is not accessible in your function
There is also the possibility to declare a const, (and then just insure the namespace is correct), like this:
const debug = true;
function newPrint($msg) {
if (\debug === true) {
echo $msg;
} else {
return false;
}
}
\newPrint("heey");//will print "heey"
so just dont use a variable, but use a const.
I have a class that does something, and when it's done it returns true, but if any of the various things go wrong it will return false. Now my question is, should status messages for such events be kept inside a class (Example1) or outside the class (Example2) where class maybe only provides error code to help distinguishing what happened.
class Example1 {
private $var;
private $status;
public function doSomething($var) {
$this->var = $var;
if (!is_numeric($this->var)) {
$this->status = 'Please provide a number';
return false;
}
if (empty($this->var)) {
$this->status = 'Please fill the field';
return false;
}
$this->status = 'Ok, you submitted a number, cool.';
return true;
}
function getStatus() {
return $this->status;
}
}
example 2:
class Example2 {
private $var;
public function doSomething($var) {
$this->var = $var;
if (!is_numeric($this->var)) {
return false;
}
if (empty($this->var)) {
return false;
}
return true;
}
}
Example 1 seems to me more convenient to use, code reads like a poem, but at the same time seems less reusable, depending on what you use class for, you might want success/error messages to have different syntax.
So basically my question would be what's the usual practice?
First example: you hard code error messages which is... bad. And you can't see the error message if you don't check $object->status later.
Second example: if something goes wrong, you know it but you don't know why.
I suggest avoiding both these ways and throwing exceptions for a more object oriented approach (I guess that's what you want, since you're using classes :).
It's completely up to you. If error messages are easier for you to understand and help you debug your code, then by all means go for it. Coming up with error codes for different errors will probably just slow down the development process, unless you want to hide the true errors from users (but in that case you have several options, one of which is to not print errors to screen at all if users might see them).
It's not what you are asking, but it's generally considered bad practice to have multiple return statements in one function. The problem is that it makes it harder to know where you exit the function, which makes it not clear what is executed. In your example, if the first test succeeds, the rest of the code is not executed. What would happen if you set some attributes afterwards ? Sometimes they will be set, sometimes they won't. To get rid of this problem, it's better to have only one return statement. More code will be executed, and you'll have to change the way you are coding a bit in order to get used to it.
Here is an example of what I mean, with the code you provide :
public function doSomething($var) {
$this->var = $var;
$result = false;
if (!is_numeric($this->var)) {
$this->status = 'Please provide a number';
}
else if (empty($this->var)) {
$this->status = 'Please fill the field';
}
else{
$this->status = 'Ok, you submitted a number, cool.';
$result = true;
}
return $result;
}
I am trying to implement error proofing to a log in script. But, I cannot get it to work? I have no idea what is going on, or why it doesn't work like I expect it to. I have tried everything, please advise.
This is the method I am calling:
public function i_exist($this_username)
{
//$host_array = null;
//$host_array = $this->collection->findOne(array("Username" => $this_username));
//if ($host_array['Username'] = $this_username)
//{
return true;
//}
//return false;
}
This is how I am calling it:
if (!empty($_POST['Username']))
{
$host = new Host();
$event = new Event();
if ($host->i_exist($_POST['Username']))
{
header("Location: http://www.drink-social.com/error.php?login=duplicate");
}
It is supposed to check the database and see if that username is already in use. But it never directs to the error page? I have even tried commenting everything out and returning true, and returning 1. Nothing?
Any advice?
When you call header(); you will also need to call exit(); otherwise the script continues running.