LeeR
LeeR

Reputation: 1636

Passing a variable through a function when passing to a function

I'm not really sure what this is called or how to search for it so hopefully this hasn't been asked too many times before.

Is it possible to pass a variable to a function inside the function variable thing... I know that doesn't make sense, so here is an example:

sendContact('Firstname Lastname', $email, $address);

function sendContact(splitWord($name), $email, $address) {
    //code here
    print_r($name);
    //result array[0] = 'Firstname';
    //result array[1] = 'Lastname';
}

function splitWord($name) {
    //code here to split words
    return $result
}

All I'm looking for is the sendContact(splitWord()) part. Is there a way to do that as that doesn't seem to work.

Upvotes: 1

Views: 88

Answers (5)

Plipus Tel
Plipus Tel

Reputation: 755

If you are 'real programmer', it's bad practice writing code like that. You should use OOP approach, if there are lots of functions involved inside a function.

class Email
{

    function splitWord($name)
    {
         // the jobs of split
    }

    function sendContact($name, $email, $address)
    {
         $receiver = $this->split($name);
         mail($receiver, $email, $address);
    }
}

Upvotes: 0

BlitZ
BlitZ

Reputation: 12168

Why not just remove some job from you?

sendContact('Firstname Lastname', $email, $address);

function sendContact($name, $email, $address) {
    $name = splitWord($name); // put inside to not duplicate for each call

    //code here

    print_r($name);

    //result array[0] = 'Firstname';
    //result array[1] = 'Lastname';
}

function splitWord($name) {
    //code here to split words
    return $result;
}

Upvotes: 1

Daryl Gill
Daryl Gill

Reputation: 5524

Perhaps you could call your other function during the call for your main.. See an example:

function sendContact($name, $email, $address) {
    //code here
    print_r($name);
    //result array[0] = 'Firstname';
    //result array[1] = 'Lastname';
}

function splitWord($name) {
    //code here to split words
    return explode (" ",$name); // Different, but made to prduce an array to show that it works
}

sendContact(splitWord('Firstname Lastname'), $email, $address);

I have called the splitWord() function during the same time as i'm calling the sendContact(); function

Upvotes: 0

Pascal Aschwanden
Pascal Aschwanden

Reputation: 158

Yes. Don't put the function call in the definition, put it in the execution like so:

function sendContact( $name, $email ) {

}
function splitWord( $name ) {
  return $result;
}

sendContact( splitWord( $name ) );

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36458

Not really. The most straightforward solution might be a simple wrapper function:

function sendAndSplitContact($name, $email, $address) {
  return sendContact(splitWord($name), $email, $address);
}

Upvotes: -1

Related Questions