How to define global functions in PHP

前端 未结 7 1298
陌清茗
陌清茗 2020-12-01 11:43

How can I define a global function which would be accessible from any page?

7条回答
  •  醉酒成梦
    2020-12-01 12:35

    Then in every page you want to use it:

    include 'include.php'; myGlobalFunction();

    -

    Put it in an include, then include it.

    This technically may not be correct, depending on the context.

    'Page' could be perceived as 'file'. For example, "You must include the function's file within each file you want to use the function".

    Once a function is defined in your program, it can be accessed from anywhere moving forward up until the program has finished executing.

    Say you have this:

    index.php:


    boot.php


    page.php


    With that, your output would be 1119342949.

    Of course, when you say 'page' you may literally mean a directly accessed stand-alone 'page file', in which case the answers from the other users will suffice. However, if you're looking to use the same function from different locations throughout your program, simply define it before you intend to use it and you can access it anywhere moving forward regardless of scope.

    However, if you're looking to use the same function from different locations throughout your program, simply define it before you intend to use it and you can access it anywhere moving forward regardless of scope.

    This of course isn't true for things like class functions, but for normal functions this remains true.

提交回复
热议问题