i dont understand how the if statement works and the function is called, why i am getting "He has more strength", i know because the strength is greater, but what i am getting there, is it a boolean? can i dump it, it shows me NULL if i put this inside the if statement
edit:i have added the return.
<?php
class Ship
{
public $name;
public $strength = 0;
public function doesGivenShipHaveMoreStrength($givenShip)
{
return $givenShip->strength > $this->strength;
}
}
$myShip = new Ship();
$myShip->name = 'TIE Fighter';
$myShip->strength = 150;
$otherShip = new Ship();
$otherShip->name = 'Imperial Shuttle';
$otherShip->strength = 50;
if ($myShip->doesGivenShipHaveMoreStrength($otherShip)) {
echo $otherShip->name.' He has more strength';
} else {
echo $myShip->name.' She has more strength';
}
?>
If statements evaluates whatever inside it's braces () . if true or 1 the block or statement will be executed. your function returned a value , and that returned value is later evaluated by the if statement. these are examples that might help you understand how if statements work. the same goes with almost every other programming language.
//example 1
if(true){
// will be executed
}else{
// will not executed
}
//example 2
if(false){
// will not executed
}else{
// will be executed
}
//example 3
if( 2 > 1){
// will be executed
}else{
// will not executed
}
//example 4
if(1){
// will be executed
}else{
// will not executed
}
//example 5
if(0){
// will not executed
}else{
// will be executed
}
//example 5
if(myFunction()){
// will be executed
}else{
// will not executed
}
function myFunction()
{
return true;
}
Your class is not written properly, it should be :
class Ship
{
public $name;
public $strength = 0;
public function doesGivenShipHaveMoreStrength($givenShip)
{
return ($givenShip->strength > $this->strength);
}
}
Then it will work as expected :) In your version, the function does return nothing, as a result when you use it, it evaluates to NULL, which is equivalent to false, and your test block fails !
I would add one more point to the recently answers.
You must add return.
Even you add the return, you shall hit your block containing "He has more strength".
Reason: you are comparing with this->strength which is 0 and your both objects have strength set to 150 & 50 accordingly. It's going to be always true.
I would suggest to compare object level values if you are really want to achieve the same functionality.
Revised Answer: You may need to adjust/fix your condition.
as per your code snippet at here
Your value of given ship shall be printed as 50 and current object value is 150 . your function is checking if 50 > 150? answer would be false and you shall hit your else.
Hope this helps
Related
I have a return statement in my function:
function fun($result)
{
$counter = 0;
while($row=mysql_fetch_array($result))
{
/*if($counter==2)
{
return $name;
}*/
$user=$row['message'];
$sql2="select username from members where id='$user'";
$result2=mysql_query($sql2);
$row2=mysql_fetch_array($result2);
$name .= $row2['username']." and ";
$counter++;
if($counter==2)
{
return $name;
}
}
}
The return block (commented) doesn't work which immediately terminates the execution of the function irrespective of the condition. But the return block if placed in position as shown in the code just works fine. Why?
I want to return only 2 rows. It seems that it should work whether it is placed before or after,because it depends on the value of the counter. Check the condition before adding new row to $name variable.First row will be added to $name and $counter is incremented,then check the condition and so on.What is wrong?
Function doesn't return anything when there are less than 3 rows even if you want to return when you reach 2, you need 3 rows minimal.
The function checks $counter in the loop after you handled your 2nd row.
So there need to be at least 3 rows for the function to return the $ name. This is weird because you want it to return then there are 2 names found.
The function doesn't necessarily terminates, but simply doesn't return anything.
Your function may never reach the return statement. You have to check for both conditions to be false and then return $name if they are. A for loop should do what you need.
function fun($result)
{
for($cnt=0; ($row=mysql_fetch_array($result)) AND $cnt<2; $cnt++)
{
$name .= 'Your Data';
}
return $name;
}
I have tested each method individually with default values and it all seems to work. There is something going on when they are all mixed together.
Here is the code and i'll do my best to write it in an easy to follow way:
Starting with the controller:
if ($active['newcliq'])
{
$newcliqid = $this->create_m->create_keyword($cliq, $cliqid);
if (!$newcliqid) {
echo json_encode(array('success' => false));
} else {
$this->logic_m->change_active($newcliqid, $cliq);
}
}
$active['newcliq'] is true or false and pulled from userdata('active')
Of course, the next thing it runs is create_keyword($cliq, $cliqid) seen below:
$this->db->insert('cliq', $insert);
$newcliqid = $this->db->insert_id();
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
Again, I have checked it all manually, and I know that $newcliqid is returning the correct insert_id and the overall function is returning the correct value.
So $newcliqid is returned to the controller and goes runs logic_m->change_active seen below:
if (!$this->logic_m->cliqidcheck($cliqid)){
$cliqid = 6;
}
The above line is what is giving me problems. No matter what value, $cliqid is ALWAYS set to 6. Whether cliqidcheck returns true or false.
Here is cliqidcheck($cliqid)
public function cliqidcheck($cliqid)
{
if ((ctype_digit($cliqid)) AND ($this->checkcliqidexist($cliqid)))
{
return true;
} else {
return false;
}
}
I have tested cliqidcheck with manually entered values and it always returns the correct value. In addition, i've flat out removed the cliqidcheck from the change_active model and it works perfectly.
I also echo'ed the variable $newcliqid in the controller and found the correct value.
I am hoping this is just a simple problem that I'm overlooking. Thanks for the help! Please let me know if more info is required.
Instead of verbal explanations, wouldn't be it better to post either the debugging code
var_dump($cliqid);
$tmp = $this->logic_m->cliqidcheck($cliqid);
if (!$tmp) {
$cliqid = 6;
}
var_dump($tmp, $cliqid);
die;
and it's output.
Even without posting it here it will convince you that if statement actually never "running regardless of true false"
Setting full error reporting also helps (with finding typos and such)
ini_set('display_errors',1);
error_reporting(E_ALL);
Also a note on excessive code. This statement
if (condition)
{
return true;
} else {
return false;
}
can (and should, in my opinion) be shortened to
return (condition);
Same goes for insert id. Why not to make it just
return $this->db->insert_id();
without all that windy
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
which is actually a mere tautology
I have inherited an application that is not doing what it's supposed to do. I have isolated the problem to the database not being properly attached. The programmer wrote this function that seemingly is suppose to evaluate whether the database is attached, calling the "attachPaymentDatabase()" function to attach it if it's not.
function attachPaymentDatabaseIfNotDoneAlready()
{
global $db;
global $hasPaymentDatabaseAttached;
// Determine if we have attached the payment tables, and if not, add them.
$hasPaymentDatabaseAttached = false;
try {
// this new way should work the best-- looking for PAY.
$alldb = queryall($db, "PRAGMA database_list;");
for ($i = 0; $i < count($alldb); $i++)
{
$alldb[$i] = array_change_key_case($alldb[$i], CASE_LOWER);
if (strtolower($alldb[$i]['name']) == 'pay')
{
debugEmail("condition 1 worked.");
$hasPaymentDatabaseAttached = true;
break;
}
}
// if its name changed this will also work
if (!$hasPaymentDatabaseAttached)
{
$r = #$db->querySingle("SELECT * FROM PAY_PARAMETER;");
$hasPaymentDatabaseAttached = true;
debugEmail("condition 2 worked.");
}
}
catch(Exception $e)
{
}
if (!$hasPaymentDatabaseAttached)
{
debugEmail("nothing worked.");
attachPaymentDatabase();
}
}
I have written a debugEmail() function that emails me a defined message with a timestamp as used above. When executing the code from the application, I can see that "condition 2 worked." is being called one second before "nothing worked.".
I don't understand how this can be. If debugEmail("condition 2 worked."); is executing, then so should too $hasPaymentDatabaseAttached = true; in which case this should not execute:
if (!$hasPaymentDatabaseAttached)
{
debugEmail("nothing worked.");
attachPaymentDatabase();
}
But it clearly is.
What is going on here?!?!?!?
No it shouldn't, because $hasPaymentDatabaseAttached is set to true in the first condition. In still nonsense at all, but it works as described.
I want to create a function in class, to create username, function will check if username exist then it will increment username like username_1. and check if this username exist or not if it exist again increment it to username_2 till new username created. I have created this function but it return me nothing.Please help me what is wrong in my code.
class a{
function check_username($username){
if($usernameexist){
return true;
}
else
{
return false;
}
}
function create_username($username) {
$__name = __FUNCTION__;
if ($this->check_username($username)) {
$n++;
$username = $username . "_" . $n;
//return $__name($username); this return fatal error.
return call_user_func('create_username', $username);
} else {
return $username;
}
}
}
No need to use recursion for this, a simple while(){} loop will do:
Plain-Jane Interator method
// your original function
function create_username($username){
// check if the username (as-is) already exists
if ($this->check_username($username)){
// use $n to keep a counter
$n = 1;
// while {username}_{n} exists, keep incrementing the counter
while ($this->check_username($username.'_'.$n)){
$n++;
/* If you don't want this to check to infinity, uncomment
* the below portion. the 100 is an arbitrary number, but use
* whatever you want as a limitation (could even make it a
* parameter in the method). Also, returning FALSE allows you to
* gracefully catch when max attempts are reached.
*
* e.g.
* if (($new_user = $obj->create_username('BradChristie')) !== FALSE){
* // user was successfully created within the max allowed attempts
* }
*/
//if ($n > 100) return FALSE
}
// return the result
return $username.'_'.$n;
}
// username was fine, return it back
return $username;
}
Recursive method
// recursive username check
public function create_username($username, $n = 0)
{
/* Same as above function, this is a check to prevent counting
* to infinity. uncomment to apply it
*/
//if ($n > 100) return FALSE;
// establish the username we're testing. if $n is 0,
// it's the original call to the function (don't add _0)
// if it's >0, it's part of the search so include it
$_username = $username . ($n > 0 ? '_'.$n : '');
// check if the username exists.
if ($this->check_username($_username))
{
// it exists, so make a call to this same function passing
// the original username and the value of n + 1 (move to next
// possibility)
return $this->create_username($username, $n+1);
}
// the name, as-is, was fine. return it
return $_username;
}
Example
Your code is wrong in several ways and, as pointed out elsewhere, your desired function is better written iteratively.
Some of the problems with your code are as follows:
You are doing your recursive check when check_username has succeeded. So, if you fail to find the original $username you are never modifying it, so never checking the modified value.
You are modifying the name passed to create_username by appending _n (for appropriate n). Since you are passing a modified name in your recursive call you will actually end up with multiple _n parts on the name.
Since you are not limiting your recursive calls, even if this was written correctly, you would eventually get nested too deep.
There is no need for recursivity in this case... A simple loop would do just perfectly:
function create_username($username) {
$original_username = $username;
$i=1;
while(! $this->check_username($username) ) {
$username = $original_username . '_' .$i++;
}
return $username;
}
I'm gonna make this too complicated, just going to break it down to the main parts.
I have a form that changes the boolean of a variable when the form gets submitted, however it gets called by a function, the function has to change the variable.
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
}
}
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true. When I do var_dump($up->yesno), it says false when it should be true. If I do this:
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
var_dump($this->yesno); // <-- outputs true
}
}
So how come I cannot get the variable to print out true in a seperate script?
EDIT:
$sql = "SELECT boolean
FROM config
WHERE boolean = 'true'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$up->updateBool();
}
else
{
header("Location: index.php?d=none");
}
This is part of the code where it gets called. I can confirm there are more than 1 record in the SQL statement.
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true
You seem to be switching to a new page, where $up will be a new object. Objects do not persist across requests. PHP "loses its memory" when you call a new page, and all variables are started from scratch.
To persist values across page requests, you would need to use something like sessions.
class updates
{
public $yesno;
function __construct(){
$this->yesno = false;
}
function updateBool()
{
$this->yesno = true;
}
}