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 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起