1

What i want is create a function that automatically generate the link with or without parameters from an array. I have created a function to generate the link but i don't know how I can also generate the link with the parameters.

  $path = array(
         'HOME_PATH' => '/home',
         'PROFILE_PATH' => '/profile/$id',
          'POST_PATH' => '/post/$id/$slug',
        );

 generateLink($path);

function generateLink($path) {
    foreach( $path as $constant => $path )
    {
        if(!defined( strtoupper($constant) ) )
        {
            define( strtoupper($constant), 'localhost/blog' . $path);
        }
    }
}

Html

<a href="<?php echo generateLink(POST_PATH); ?>">Home Page</a>

<a href="<?php echo generateLink(POST_PATH, $id, $slug); ?>">Post Details</a>

<a href="<?php echo generateLink(PROFILE_PATH, $id); ?>">Profile</a>
0

1 Answer 1

1

Another way would be to use vsprintf along with an array parameter.

So you set a defined format first using the path:

$path = array(
    'HOME_PATH' => '/home/',
    'PROFILE_PATH' => '/profile/%s',
    'POST_PATH' => '/post/%s/%s',
);

Then you apply vsprintf on the loop using an array argument with the id and slug:

function generateLink($args) { // <feed an array>
    $path = array(
        'HOME_PATH' => '/home/',
        'PROFILE_PATH' => '/profile/%s',
        'POST_PATH' => '/post/%s/%s',
    );
    foreach ($path as $constant => $uri) {
        $constant = strtoupper($constant);
        if (!defined($constant)) {
            define($constant, 'localhost/blog' . vsprintf($uri, $args));
        }
    } 
}

generateLink([$id, $slug]); // use the function to generate the definitions
// just make sure the arguments are defined before invoke the function

Then use the definitions as you normally would:

<a href="<?php echo HOME_PATH; ?>">Home Page</a>
<a href="<?php echo POST_PATH; ?>">Post Details</a>
<a href="<?php echo PROFILE_PATH; ?>">Profile</a>

Sidenote: Another variation would be to use generateLink($id, $slug) and use func_get_args(). But still, you get an array and use it in vsprintf.

Sign up to request clarification or add additional context in comments.

2 Comments

but how i can pass arguments to PROFILE_PATH in html?
@bdroid you don't need to do so as it is already part of the function, unless you have specific reason as to why it needs to be defined outside, you can define it outside, the concept of vsprintf should be the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.