duansha3771 2017-04-04 18:44
浏览 41
已采纳

函数和if中的其他PHP

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';

}


?>
  • 写回答

3条回答 默认 最新

  • du67560 2017-04-04 19:53
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答