Jump to content

[SOLVED] Need help with a static array please, reproducible code included (5 lines)


EricIsGood

Recommended Posts

<?php
Class users { 
public static $usersToCacheByID = array();
}

users::$usersToCacheByID[] = 'User1';
users::$usersToCacheByID[] = 'User2';
echo '<pre>usersToCacheByID ' . users::$usersToCacheByID . '</pre>';
?>

 

I expect this to print out 'User1' and 'User2' when I print the array.

 

Thanks for your help,

 

-Eric

You would need to create an instance of the users class first:

 

$u = new users();
u::$usersToCacheByID[] = 'User1';
u::$usersToCacheByID[] = 'User2';
echo 'usersToCacheByID ' . users::$usersToCacheByID . '';

The class doesn't look static to me. The array is.  ;)

 

Sorry if I'm being dense but...

 

I tried typing:

static class User {

 

Which gave me a fatal error...

 

According to this page:

http://bryanstamour.com/?p=20

 

I don't need to do anything special to make the class static, so long as it's members are static.

 

Obviously I'm missing something...

 

Thanks for the help,

 

-Eric

 

Thanks... following that example, I did:

 

<?php
class Foo
{
   public static $my_static = 'foo';
}
print Foo::$my_static . "\n";

?>

 

Which works perfect....

 

the only difference from my example in my first post seems to be that I'm using an array....

Here's another example...

 

example 1 doesn't work

example 2 does work....

 

I'm so confused...

 

<?php

//example 1:
Class users { 
public static $usersToCacheByID = array();
}

users::$usersToCacheByID[] = 'User1';
users::$usersToCacheByID[] = 'User2';
echo '<pre>usersToCacheByID ' . users::$usersToCacheByID . '</pre>';



//example 2:
class Foo {
public static $my_static;
}

Foo::$my_static = 'hi';
echo Foo::$my_static . "\n";

?>

Please learn how to print Arrays out.  And yes it did work, you should have mentioned it printed out 'Array'.

 

Class users { 
   public static $usersToCacheByID = array();   
}
   
users::$usersToCacheByID[] = 'User1';
users::$usersToCacheByID[] = 'User2';
echo 'usersToCacheByID: 
';
foreach(users::$usersToCacheByID as $key => $value) {
echo 'key: ' . $key  . ' value: ' . $value . '
';
}

echo '';

Please learn how to print Arrays out.  And yes it did work, you should have mentioned it printed out 'Array'.

 

Thanks for the help.

 

I was originally using print_r.  Between all my moving code arround I lost the print_r call without realizing it.

 

All is good now.

 

Best,

 

-Eric

print_r() dumps out the keys/values, but you have no control, although it's good for debugging.  If you want to format them in any way you have use something like a foreach loop.  Glad it works now!  ;D

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.