Jump to content

Accessing PW API within a function (Newbie Question)


tourshi
 Share

Recommended Posts

Hi, 

I'm new to PW and still a novice in PHP. I was just wondering how does one access PW within  a function? 

do I pass the entire $page variable to getTitle()? or do I use global $page within the function...I'm confused.. Especially considering there must be a performance penalty for passing entire page variable when I only need a few variables from it (for example $page->long_title, $page->menu_title, $page->short_title).

function getTitle() {
$long_title = $page->long_title;
$title = !empty($long_title) ?  $long_title : $page->title;
return $title;
}

Link to comment
Share on other sites

function getTitle() {
  $long_title = $page->long_title;
  $title = !empty($long_title) ?  $long_title : $page->title;
  return $title;
}

Hi @tourshi, welcome to PW.

If you want do "things" with / from a page in a function, you best pass the $page as parameter or get its handle with the wire() function:

function getTitle($page) {
    $t = $page->title;
function getTitle() {
    $page = wire("page");
    $t = $page->title;

But if you only want one of two field values, depending if it is populated or not, as I can see from your code, you don't need a function for that. You can use it directly in your template with an OR selector as follows:

$t = $page->get("long_title|title");

This will give you the value of long_title if there is one, OR, if it is empty, it gives you the value of title.

Coming back to the function: fastest way is to pass the variable into the function, because the variable is an object what is passed by reference. There is no drawback or overhead, its the fastest way.

If you, for what ever reason, cannot pass a API variable to a function, you always can get there handles via the wire("nameofapivar") function. This works everywhere, but has a (very little) overhead. Also I don't think it is measurable with a few calls, (less than 100).

Edited by horst
  • Like 8
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...