简体   繁体   中英

PHP Defining Function Logical

I am just starting out learning php, and I was wondering someone can help me out with the logical of defining functions. I can't seem to wrap my head around it.

Simple Example:

<?php

function hello($word) {
  echo "Hello $word";
}

  $name = "John";
  strtolower(hello($name))

?>

I know if I use return instead of echo in the function and then echo it outside defining the function, the "strtolower" applies, but in this example it doesn't. I don't get how php is interpreting it. Thanks in advance.

Imagine a function is a box of unknown content. You put something in and something comes out - meaning you have parameters and something to be returned .

In your code example you don't return anything, instead echo some string.

function hello($word) {
//             ^ parameter
  return "Hello $word";
}

$name = "John";
strtolower(hello($name));

To explain a bit further, you can look at your original code this way:

echo strtolower(hello("John"));
     ^          ^--- call hello("John")
     |                something happens (your echo)
     |               hello() ended without return, return NULL by default
     |--- call strtolower( NULL )
            something happens
          strtolower() returned ""

But you want it to be like this:

echo strtolower(hello("John"));
     ^          ^--- call hello("John")
     |                something happens
     |               hello() return "Hello John"
     |--- call strtolower("Hello John")
            something happens
          strtolower() returned "hello john"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM