Question

I am learning a bit about functions to understand their use a bit more. I have come across an issue I can't find an answer to, well at least not one I can relate the issue to.

<?php

// some variables.

$firstName = "foo";
$surname = "bar";

//The function

function myName ($firstName, $surname) {

    echo "Hello $firstName $surname. <br>";

}

// The output.

myName($firstName, $surname);

?>

As you can see if both $firstName and $username exist then all is well however if $surname does not exist and the script somewhere else that bring the information in only checks for the existence of $first_name then the function is going to fail.

So my question is how can I test within the function whether the values for both variables exist and is there a way to prevent it failing in the event for example that only $firstName exists.

Était-ce utile?

La solution

Try this:

$firstName = "foo";
$surname = "bar";

function myName ($firstName, $surname) {

if(isset($firstName) && isset($surname))
{    echo "Hello $firstName $surname. <br>";
}

else if(isset($firstName))
{    echo "Hello $firstName. <br>";
}

}

myName($firstName, $surname);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top