Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using constants as default function values in PHP

Tags:

Is this legal?

<?php

function ftw($foo = 'pwnage', $nub = MENU_DEFAULT_VALUE, $odp = ODP_DEFAULT_VALUE) {
      //lots_of_awesome_code
}

?>

where MENU_DEFAULT_VALUE and ODP_DEFAULT_VALUE are constants defined previously in the file.

like image 626
Nick Heiner Avatar asked Aug 04 '09 18:08

Nick Heiner


People also ask

What is the purpose of constant () function in PHP?

The constant() function returns the value of a constant. Note: This function also works with class constants.

Can I use const in PHP?

PHP - Class ConstantsClass constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.

How do we define default function parameters in PHP?

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. $str = 'This is a string, '; add_some_extra($str);

Which option will print the value of the constant const in PHP?

Basic Usage of the const Keyword to Declare Constants For this example, we will declare a new constant using PHP's const keyword. We will name this constant “ WEBSITE ” and assign it the value “ pimylifeup.com “. Once declared, we will use the echo function to print the value of the constant to the screen.


1 Answers

Yes, that is legal.

From the manual:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Constants fit that bill perfectly.

like image 90
zombat Avatar answered Sep 30 '22 05:09

zombat