Jump to content

PageArray issue on page fields


Roope
 Share

Recommended Posts

Hi all!

This odd behaviour came up on one live site I build just little while ago. I have two Page fields at home page:

  • advertize_homepage
  • advertize_sidebar

At homepage template I get all pages from both and echo images to slider:

$slides = $page->advertize_homepage;
$slides->append($page->advertize_sidebar);
$slides->shuffle();

foreach ($slides as $slide) {
  ...
}

I noticed that later when I get $page->advertize_homepage and loop results, it holds also pages that are set to $page->advertize_sidebar. Array is also shuffled.

Here's reduced testcase:

<pre><?php 

  echo 'items before: ' . count($page->advertize_homepage) . "\n"; 

  $slides = $page->advertize_homepage;
  $slides->append($page->advertize_sidebar);
  $slides->shuffle();

  echo 'items after: ' . count($page->advertize_homepage); 

?></pre>

Result:

items before: 8
items after: 15

I'm using latest dev, tested on PHP 5.3.23 and 5.4.10

Link to comment
Share on other sites

Hi!

Try the following:

<pre><?php

  echo 'items before: ' . count($page->advertize_homepage) . "\n";

  $slides = clone $page->advertize_homepage;
  $slides->append($page->advertize_sidebar);
  $slides->shuffle();

  echo 'items after: ' . count($page->advertize_homepage);

?></pre>
Link to comment
Share on other sites

@Roope: Assigning an object does not copy the contents of the object, only its identifier. After the assignment to $slides, the variable holds the same object identifier as $page->advertize_homepage. So you're actually using the very same object there, which explains the behavior you're facing.

Like Fokke said, you should use clone to make a copy of an object to keep the original object intact. See http://php.net/manual/en/language.oop5.references.php for more information on objects, object identifiers and references in PHP5.

  • Like 1
Link to comment
Share on other sites

Thanks guys! There's no stupid questions, only stupid people. Being such a OOP noob this object behaviour was completely new to me. Wonder why I haven't faced this earlier though.

Could it be worth to add a mention about this to the default template head.inc?

// In this case we also want the homepage to be part of our top navigation, 
// so we prepend it to the pages we cycle through:

$homepage = $pages->get("/"); 
$children = $homepage->children;
$children->prepend($homepage);

Because it says in this case, some another freshman could think that second line is there to keep $homepage->children intact.


 

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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...