在用户定义的函数中使用标志

时间:2017-05-20 00:14:33

标签: php

我有一个我创建的脚注功能。我想让用户选择让他们的脚注显示为数字或字母。以下是我如何调用该函数:

newFootnote($text,"letters")
newFootnote($text,"numbers")
newFootnote($text,true)
newFootnote($text,false)

如果使用bool,true可以使用数字,false可以使用字母。不过,我更愿意使用以下格式:newFootnote(LETTER)newFootnote(NUMBER)

我知道内置函数有你使用的标志。例如,preg_match_allPREG_OFFSET_CAPTUREPREG_PATTERN_ORDER等。是否可以在用户定义的函数中使用标记?

3 个答案:

答案 0 :(得分:0)

是的,使用define()来定义命名常量aka flag

define('NAMED', 'letters');
newFootnote($text, NAMED);

答案 1 :(得分:0)

对于全球范围

define('NUMBERS',true);
define('LETTERS',false);

在课程中,您也可以使用class constants

答案 2 :(得分:0)

简答:是的,可以在用户定义的函数中使用标志。 简而言之,A旗使用案例有三种:

  • 内置函数标志
  • PHP扩展函数标志
  • 用户定义的功能标志

内置的php函数,你可以看到:

echo PREG_OFFSET_CAPTURE."<br>";// output 256

一个php exntesion,安装后,你可以使用它的常量,好像它们是核心的php函数标志一样,

如果您想为自己的功能定义自己的标志,可以:

define ("LETTER", "letters");
define ("NUMBER", "numbers");

function newFootnote($text,$flag){
     if ($flag==NUMBER){
         // code to display foot notes as numbers 
        echo "The numbers are :$text <br />";
     }elseif($flag==LETTER){
         //  code to display foot notes as letters
        echo "The letters are :$text <br />";
     }else{
         // choose between a default behavior, or rising an error
        echo "error   <br />";
     }
}
newFootnote (" some random text to test", NUMBER); // output The numbers are : some random text to test 
newFootnote (" some random text to test", LETTER); // output The letters are : some random text to test
newFootnote (" some random text to test",NULL); // error 
  

但是,我更喜欢使用以下格式:newFootnote(LETTER)或newFootnote(NUMBER)

实际上你不能这样称呼它,因为你必须提供第一个参数,即$ text,你会这样称呼它:

newFootnote($text,LETTER);//or
newFootnote($text,NUMBER);

如果你想隐藏常量定义和/或在你的程序中使它们可用,那么你可以将它们放在一个文件中(理想情况下是函数定义)并在需要时包含它,让该文件为notesFunctions.php,put在其中:

define ("LETTER", "letters");
define ("NUMBER", "numbers");

function newFootnote($text,$flag){
     if ($flag==NUMBER){
         // code to display foot notes as numbers 
        echo "The numbers are :$text <br />";
     }elseif($flag==LETTER){
         //  code to display foot notes as letters
        echo "The letters are :$text <br />";
     }else{
         // choose between a default behavior, or rising an error
        echo "error   <br />";
     }
}

然后在你的程序中,根据文件的位置(这里假设它们在同一个文件夹中),你把:

include ("notesFunctions.php");
/* then you call your function as needed and the output still be the same as 
before */
    newFootnote (" some random text to test", NUMBER); // output The numbers are : some random text to test 
    newFootnote (" some random text to test", LETTER); // output The letters are : some random text to test
    newFootnote (" some random text to test",NULL); // error