Solved

static array in PHP object

Posted on 2011-03-02
14
731 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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 

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
 
LVL 109

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 109

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 109

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 109

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
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 create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

777 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