Jump to content

[SOLVED] Simple class... Simple functions... Simple variable... I don't get it!


asafadis

Recommended Posts

Ok... so I'm hoping this is pretty simple.  I would think so... but I've never done this before.

 

Goal:

Store items into an array from anywhere in the application and retrieve an item from that array from anywhere in the application.  This implies that unless I manually empty the array, it should "permanently" keep the data stored in it.

 

Problem:

I can only pull data (get) from the array in the same page I stored the data (add) in the first place.  If I go to another page, and try to pull the data, it won't work.

 

Question:

Where do I instantiate the variable I need and what should the syntax be?

 

This is what I've got:

 

functions.php

class nav() {
   function add($item) {
      array_push($this->nav_array,$item);
   }

   function remove() {
      array_pop($this->nav_array);
   }
   
   function get() {
      return $this->nav_array[0];
   }
}

$nav = new nav();

 

page_works.php

include('functions.php');
$nav-add('foo bar');
echo $nav->get();

 

page_does_not_work.php

include('functions.php');
echo $nav->get();

 


 

Any ideas?  I'd really aprpeciate any help you can give me!

The problem isn't syntax, it's that PHP is basically stateless.  That is, your separate scripts won't automatically know what happening in the other files.  You need to manually pass your objects from script to script.  In your case, try using sessions:

 

<?php
   //Functions.php

   class nav() {
      private nav_array = array();

      function add($item) {
         array_push($this->nav_array,$item);
      }

      function remove() {
         array_pop($this->nav_array);
      }
   
      function get() {
         return $this->nav_array[0];
      }
   }

   /*----------------------------
   The scripts that makes it:
   ----------------------------*/

   session_start();
   include('Functions.php');

   $nav = new Nav();

   //do nav things

   $_SESSION['nav'] = serialize($nav);

   /*---------------------------
   The script that takes it
   ---------------------------*/

   session_start();
   include('Functions.php');

   $nav = unserialize($_SESSION['nav']);

   echo $nav->get();

?>

 

There may be other ways to do this, but I've used this method before and it works.

to "remember" the data across pages, $_SESSIONS are where it's at.

 

take a read up here regarding serialising the object, which you'll need to do to store it in your session:

http://uk2.php.net/manual/en/language.oop.serialization.php

 

then sessions themselves:

http://uk.php.net/sessions

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.