简体   繁体   English

PHP定义函数逻辑

[英]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. 我刚开始学习php,我想知道有人可以通过定义函数的逻辑来帮助我。 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. 我知道如果我在函数中使用return而不是echo,然后在定义函数之外回显它,则“ strtolower”适用,但在此示例中不适用。 I don't get how php is interpreting it. 我不了解php是如何解释它的。 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. 在您的代码示例中,您不返回任何内容,而是echo一些字符串。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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