简体   繁体   中英

Echo or return a function in PHP

I have this very simple question, but I am searching for hours now, and cannot find the answer.

With my function wzd_url() I make my urls.

For example wzd_url(2) gives me: http://www.mywebsite.com/douchedeur-glassoort

I use this function in my whole project and works fine. But know I want to use this function as follows:

echo = '<a href="' . wzd_url(2) . '">test</a>';

or:

function output() {
$output = '<a href="' . wzd_url(2) . '">test</a>';
echo $output;   

}

output();

it outputs: http://www.mywebsite.com/douchedeur-maten test

And I read some other articles about this subject, and they said I need to change echo to return in my wzd_url() function, but if I do that this function doesn't work anymore.

Can someone help me with this?

In this array I store some data for my pages:

$wzd_pages = array(
    0   => array('Intro', 'douchedeur-intro'),
    1   => array('Maten', 'douchedeur-maten'),
    2   => array('Glassoort', 'douchedeur-glassoort'),
    3   => array('Scharnieren', 'douchedeur-scharnieren', 'Scharnieren en draairichting'),
    4   => array('Deuropener', 'douchedeur-deuropener'),
    5   => array('Coating', 'douchedeur-coating'),
    6   => array('Prijs / Bestellen', 'douchedeur-prijs'));

With this function I make my URLs:

// URL  
function wzd_url($page) {
    global $wzd_pages;
    echo bloginfo('wpurl') . '/' . $wzd_pages[$page][1];
}   

if you change echo to return, your function will "return" that link but it wont show it. Then you need echo in you template for example:

echo <a href="' . wzd_url(2) . '">test</a>

In summary - when you need to move echo from your function to your template

I suggest you create 2 function as below :-

function wzd_url($page) {
global $wzd_pages;
    if(is_array($wzd_pages[$page]) && count($wzd_pages[$page])){
        $_return['url'] = bloginfo('wpurl') . '/' . $wzd_pages[$page][1];
        $_return['text'] = $wzd_pages[$page][0];
        return $_return;
    }else{
        return false;
    }
}

function anchor($page){

    if($url = wzd_url($page)){
?>
<a href="<?php echo $url['url'];?>"><?php echo $url['text']?></a>
<?php
    }

}

I needed to modify the wzd_url(); function, because it uses bloginfo(); , and this function prints the string. So I need get_bloginfo(); or better: site_url();

// URL  
function wzd_url($page) {
    global $wzd_pages;
    echo siteurl('wpurl' . '/' . $wzd_pages[$page][1] );
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM