PHP 8.5.0 Alpha 1 available for testing

Voting

: six minus three?
(Example: nine)

The Note You're Voting On

Dennis Robinson from basnetworks dot net
16 years ago
This function comes in handy, and I believe is the only solution, when you have an optional parameter that can take any type of data.

For example:

<?php

// $data can be of any type, including null
function my_function($name, $data = null)
{
if (
$data !== null)
{
// Do something with $data
// If you call my_function('something'), this WILL NOT be reached
// If you call my_function('something', null), this WILL NOT be reached
}
}

?>

The problem with the above function is that you will never be able to use null as the value for $data. To fix this, use func_num_args() like so:

<?php

// $data can be of any type, including null
function my_function($name, $data = null)
{
if (
func_num_args() >= 2)
{
// Do something with $data
// If you call my_function('something'), this WILL NOT be reached
// If you call my_function('something', null), this WILL be reached
}
}

?>

This solution works because func_num_args() reports exactly how many arguments were passed when the function was called. It does not take into account when default argument values are used.

<< Back to user notes page

To Top