Solved

static array in PHP object

Posted on 2011-03-02
14
721 Views
Last Modified: 2012-05-11
Hi I have a static array in a php object, namely a database table object.
Is it possible to initialize this static array with column names dynamically ?
I don't want to type in the long list of meaningless field names. I would rather
retrieve via SQL and initialize $dbfields

 Class MyTable  extends DatabaseObject {

   static $dbfields = (......)
 }

0
Comment
Question by:Rozamunda
  • 6
  • 4
  • 4
14 Comments
 
LVL 9

Expert Comment

by:AriMc
ID: 35022262
What database engine are you using?

0
 

Author Comment

by:Rozamunda
ID: 35022278
DB2
0
 
LVL 9

Expert Comment

by:AriMc
ID: 35022337
Ok, I'm not familiar with DB2, but typically you'd use a database engine specific query like "desc mytable" (works for Oracle and MySQL) and then process the results just like you'd do to any other query to fill your array.

Try that "desc mytable" and if it doesn't work, study DB2's manuals to find a way to describe the structure of a table.

0
 

Author Comment

by:Rozamunda
ID: 35022389
yes, I have system tables that keep column names. My question was rather if it is possible, i guess
it is. Should I use static method to initialize this static array ?.
0
 
LVL 9

Expert Comment

by:AriMc
ID: 35022515
Static class members are available without instantiation of the class but then they must be literal assignments, so I'd say you can not make them static if you want to read the values dynamically from the database.

0
 

Author Comment

by:Rozamunda
ID: 35022531
I found this:

http://stackoverflow.com/questions/693691/php-how-to-initialize-static-variables

according to this link it is possible ?
0
 
LVL 9

Expert Comment

by:AriMc
ID: 35022616
Hmm... okay, it looks like it is possible but IMHO it violates pretty much all the things about static variables. In order to that to work in your case, you must be sure your database connection is open etc.

You can try but I'd still make those arrays non-static just avoid shooting myself in the foot by running into strange problems later, even if it works fine when test it the first time.

0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 35022824
There's nothing wrong with calling the array "static."  This example is with MySQL but it shows the concept using the class constructor to load the array.
<?php // RAY_temp_rozamunda.php
error_reporting(E_ALL);


class Rozamunda
{
    protected static $columns;

    public function __construct($table)
    {
         // CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
        $db_host = "localhost"; // PROBABLY THIS IS OK
        $db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
        $db_user = "??";
        $db_word = "??";

        // OPEN A CONNECTION TO THE DATA BASE SERVER
        // MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
        if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
        {
            $errmsg = mysql_errno() . ' ' . mysql_error();
            echo "<br/>NO DB CONNECTION: ";
            echo "<br/> $errmsg <br/>";
        }

        // SELECT THE MYSQL DATA BASE
        // MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
        if (!$db_sel = mysql_select_db($db_name, $db_connection))
        {
            $errmsg = mysql_errno() . ' ' . mysql_error();
            echo "<br/>NO DB SELECTION: ";
            echo "<br/> $errmsg <br/>";
            die('NO DATA BASE');
        }

        // GET THE COLUMN NAMES AND ASSIGN THEM TO THE STATIC ARRAY
        $sql = "SHOW COLUMNS FROM $table";
        $res = mysql_query($sql) or die( mysql_error() );
        while ($show_columns = mysql_fetch_assoc($res))
        {
            $this->columns[] = $show_columns["Field"];
        }
    }

    public function get_columns()
    {
        return $this->columns;
    }
}

;

$r = new Rozamunda('visitors');
$c = $r->get_columns();

echo "<pre>";
var_dump($c);

Open in new window

0
 
LVL 9

Expert Comment

by:AriMc
ID: 35022865
Ray: Would that change anything? Your __construct still gets called upon every creation of an instance of the class.

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 35022937
Yes, but if you instantiate the class only once, and then extend it you might be able to achieve the objective.  

To be honest, I do not see any real virtue in making it static.  It would depend on the way the script was written and it would probably not be much of a performance burden to reload the table in the constructor for every instance.
0
 
LVL 9

Expert Comment

by:AriMc
ID: 35022959
Rozamunda: It might help to know why you want to make this array static and yet dynamically loaded.

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 35023056
Agreed - that is a good question.  The use I have found for static data is when you want something like an incremental counter inside a function.  
<?php // RAY_static_variable.php
error_reporting(E_ALL);


// DEMONSTATE THE USE OF A STATIC VARIABLE


// ONE WAY TO DO IT - RETURN THE TOTAL FROM THE FUNCTION
function get_my_results($keyword)
{
    // DEFINE A STATIC VARIABLE
    static $total;

    // INITIALIZE THE STATIC VARIABLE
    if (!isset($total)) $total = 0;

    // IF THIS IS THE KEYWORD WE WANT, ADD TO THE TOTAL
    if ($keyword == "learning php")
    {
        $total = $total + 1;
    }

    // RETURN THE TOTAL VALUE
    return $total;
}
// END FUNCTION

$k = get_my_results("learning php");
echo "<br/>$k";  // 1

$k = get_my_results("learning php");
$k = get_my_results("learning php");
$k = get_my_results("learning php");
echo "<br/>$k"; // 4

$k = get_my_results("NOT learning php");
echo "<br/>$k"; // STILL 4

$k = get_my_results("learning php");
echo "<br/>$k";  // 5

Open in new window

0
 

Author Comment

by:Rozamunda
ID: 35023093
I plan to add an init script called only once where for all my tables objects i will call static function
to initialize list of fields. This way it will be called only once for each class.

The fields have strange names like : WERTYX , I want to map them to column names, so it would be
easier to maintain when updating etc
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 35023143
I guess you can use static vars if you want, but you might want to read the part about them on this page:
http://php.net/manual/en/language.variables.scope.php

You can load them and change them and they persist across repeated calls to the functions.  What you cannot do is load them by using an expression.  You can, however, assign a value later by using an expression.

HTH, ~Ray
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now