zoukankan      html  css  js  c++  java
  • PHP学习五--函数

    1.PHP函数的定义方式:     1.使用关键字“function”开始     2.函数名可以是字母或下划线开头:function name()     3.在大括号中编写函数体:

    function name() {
        echo 'Eric';
    }

    通过上面的步骤,我们就定义了一个简单的函数,当我们需要的时候,就可以在代码中调用这个函数,调用方法为函数名+参数,例如:name();

    2.PHP的函数可以没有参数,也可以有若干个参数,多个参数称之为参数列表,采用逗号进行分割,参数类似于一个变量,调用时用来传递数据到函数体中。通过传递参数可以使函数实现对参数的运算,得到我们想要的结果。

    参数的变量名可以自由指定,但最好能够表达相关的意思,常用的设定参数的方法为:

    function sum($a, $b) {
        echo $a + $b;
    }
    //在这里调用函数计算1+2的值
    sum(1,2);

    3.使用return关键字可以使函数返回值,可以返回包括数组和对象的任意类型,如果省略了 return,则默认返回值为 NULL。

    function add($a) {
        return $a+1;
    }
    $b = add(1);

    函数不能返回多个值,但可以通过返回一个数组来得到类似的效果。

    function numbers() {
        return array(1, 2, 3);
    }
    list ($one, $two, $three) = numbers();

    4.内置函数指的是PHP默认支持的函数,PHP内置了很多标准的常用的处理函数,包括字符串处理、数组函数、文件处理、session与cookie处理等。

    我们先拿字符串处理函数来举例,通过内置函数str_replace可以实现字符串的替换。下面的例子将“jobs”替换成“steven jobs”:

    $str = 'i am jobs.';
    $str = str_replace('jobs', 'steven jobs', $str);
    echo $str; //结果为“i am steven jobs”

    5.函数是否存在

    当我们创建了自定义函数,并且了解了可变函数的用法,为了确保程序调用的函数是存在的,经常会先使用function_exists判断一下函数是否存在。同样的method_exists可以用来检测类的方法是否存在。

    function func() {
    }
    if (function_exists('func')){
        echo 'exists';
    }

    类是否定义可以使用class_exists。

    class MyClass{
    }
    // 使用前检查类是否存在
    if (class_exists('MyClass')) {
        $myclass = new MyClass();
    }

    PHP中有很多这类的检查方法,例如文件是否存在file_exists等。

    $filename = 'test.txt';
    if (!file_exists($filename)) {
        echo $filename . ' not exists.';
    }
  • 相关阅读:
    401. Binary Watch
    46. Permutations
    61. Rotate List
    142. Linked List Cycle II
    86. Partition List
    234. Palindrome Linked List
    19. Remove Nth Node From End of List
    141. Linked List Cycle
    524. Longest Word in Dictionary through Deleting
    android ListView详解
  • 原文地址:https://www.cnblogs.com/moxuexiaotong/p/6605890.html
Copyright © 2011-2022 走看看