0

I want to get my website page title through a function

First I get the Page Name from a function...

function pagetitle() {
global $th, $ta, $tp, $ts, $tc; // <---- Getting the variable value from outside function
global $bl, $qt;
$tit = ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
if($tit == "Index") {
    echo $th;
}
elseif($tit == "About-us"){
    echo $ta;
}
elseif($tit == "Projects"){
    echo $tp;
}
elseif($tit == "Services"){
    echo $ts;
}
elseif($tit == "Contact-us"){
    echo $tc;
}
elseif($tit == "Blog"){
    echo $bl;
}
elseif($tit == "Quotation"){
    echo $qt;
}

}

Then I tried to get the page title in the format of PageName | PageTitle or PageTitle | PageName...

function getOrg_title(){
$tit = "";
$block = " | ";
global $sl;
$org = $sl['app_org'];
if($sl['title_before'] === 'yes'){
    $tit = $org.$block.\pagetitle(); //<----- This should be like "Raj | This is my website"
}  else {
    $tit = \pagetitle().$block.$org; //<----- This should be like "This is my website | Raj"
}
echo $tit;
}

But not happening...

$tit = $org.$block.\pagetitle(); //<----- Output is "This is my websiteRaj |"

And

$tit = \pagetitle().$block.$org; //<----- Output is "This is my website | Raj"

What should I do ?

Raja
  • 772
  • 1
  • 15
  • 38

1 Answers1

3

You expect pagetitle() to return the page's title, but instead in your code you use echo.
echo will print out the title to the client rather than return it to the caller.

So change you echo $...; to return $...; and do echo pagetitle(); whereever you use it directly.

If this can not be done, you could extend your function to

pagetitle($echo = true)
{
    // ...
    if(/* ... */) {
        $ret = $th;
    } elseif(/* ... */) {
        $ret = ...;
    } elseif(/* ... */) {
        $ret = ...;
    }
    // And so on ...

    if($echo)
        echo $ret;

    return $ret;
}

Now in your wrapper function call pagetitle(false) to prevent the echo and still get the title from it.


About the backslash: \pagetitle()
The backslash is the namespace separator. Since you are not using namespacing here, all functions will be on the root namespace.
In this case - if you are using PHP 5.3 or above - you can use it or leave it out.

Community
  • 1
  • 1
Lukas
  • 1,479
  • 8
  • 20
  • Hi Lukas, I have done as per your instruction but there is a new problem. I am getting the output like `PageTitlePageName | PageTitle` if the database field set to 'yes' otherwise the output is `PageTitlePageTitle | PageName`. – Raja May 26 '14 at 06:41
  • Then you either did not replace all `echo`s in `pagetitle()` or you call `pagetitle()` or `pagetitle(true)` in `getOrg_title()`. Using `pagetitle(false)` after changing the function like I explained, would prevent the title from `echo`ing twice. – Lukas May 26 '14 at 09:59
  • Thanks Lukas, I have changed my code by implementing your idea and got the result. Thanks again. – Raja May 26 '14 at 13:52