Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
iwato

Class Variable Declaration

Recommended Posts

BACKGROUND:  I am now running with PHP 5.5.38, and things are nearly back to normal.  My error messages have returned, and things that once worked, now function well again.  This said, I wish to make good on the pain and disappointment that I suffered and am requesting your help to do so.

REQUEST:  Please find below a PHP class that I created in order to gather data from my database.  It works fine in my current PHP environment and produces the expected results.  It has been upgraded to handle multiple languages and editions of the same letter number.  In addition, I have included a list of suspect variables -- namely, variables whose undeclared status may have been a source of difficulty while running in my previous PHP 5.6.33 environment.

class Newsletter {
    public $letter_no;
    public $letter_lang;
    public $mysqli_obj;
    public $letter_ed;
    public $pc_total;
    public $podcasts;

    public function __construct($letter_no, $letter_lang, $mysqli_obj, $letter_ed = 1) {
        $this->letter_no = $letter_no;
        $this->letter_lang = $letter_lang;
        $this->mysqli_obj = $mysqli_obj;
        $this->letter_ed = $letter_ed;
    }

    public function get_letter_data() {
        $sql = "SELECT letter.*, qa.*
                FROM sevengates_letter AS letter
                JOIN sevengates_qa AS qa
                    ON letter.letter_no = qa.letter_no
                    WHERE letter.letter_no = ? AND letter.letter_lang = ?
                    ORDER BY letter.letter_ed DESC";
        $mysqli_stmt = $this->mysqli_obj->stmt_init();
        $mysqli_stmt->prepare($sql);
        $mysqli_stmt->bind_param('is', $this->letter_no, $this->letter_lang);
        $mysqli_stmt->execute();
        $meta = $mysqli_stmt->result_metadata();
        while ($field = $meta->fetch_field()) {
            $params[] = &$row[$field->name];
        }
        call_user_func_array(array($mysqli_stmt, 'bind_result'), $params);
        while ($mysqli_stmt->fetch()) {
            foreach($row as $key => $val) {
                $c[$key] = $val;
            }
            $prelim_result[] = $c;
        }
        foreach ($prelim_result as $arr) {
            foreach ($arr as $name => $value){
                $letter_results[$name] = $value;
            }
        }
        return $letter_results;
    }

    public function get_nextletter_data() {
        $next_letter_no = $this->letter_no + 1;
        $sql = "SELECT letter_no, letter_title, letter_abstract FROM sevengates_letter WHERE letter_no = ?";
        $mysqli_stmt = $this->mysqli_obj->stmt_init();
        $mysqli_stmt->prepare($sql);
        $mysqli_stmt->bind_param('i', $next_letter_no);
        $mysqli_stmt->execute();
        $meta = $mysqli_stmt->result_metadata();
        while ($field = $meta->fetch_field()) {
            $params[] = &$row[$field->name];
        }
        call_user_func_array(array($mysqli_stmt, 'bind_result'), $params);
        while ($mysqli_stmt->fetch()) {
            foreach($row as $key => $val) {
                $c[$key] = $val;
            }
            $prelim_result[] = $c;
        }
        $mysqli_stmt->free_result();
        foreach ($prelim_result as $arr) {
            foreach ($arr as $name => $value){
                $nextletter_results[$name] = $value;
            }
        }
        return $nextletter_results;
    }

    public function get_podcasts() {
        $sql = "SELECT podcast_ref FROM sevengates_podref WHERE letter_no = ?";
        $mysqli_stmt = $this->mysqli_obj->stmt_init();
        $mysqli_stmt->prepare($sql);
        $mysqli_stmt->bind_param('i', $this->letter_no);
        $mysqli_stmt->execute();
        $meta = $mysqli_stmt->result_metadata();
        while ($field = $meta->fetch_field()) {
            $params[] = &$row[$field->name];
        }
        call_user_func_array(array($mysqli_stmt, 'bind_result'), $params);
        while ($mysqli_stmt->fetch()) {
            foreach($row as $key => $val) {
                $c[$key] = $val;
            }
            $prelim_result[] = $c;
        }
        $i = 1;
        foreach ($prelim_result as $arr) {
            foreach ($arr as $name => $value) {
                $name = $name . '_' . $i;
                $podcasts[$name] = $value;
            }
            $i++;
        }
        $this->pc_total = count($podcasts);
        return $podcasts;
    }

    public function get_podcasts_data($podcasts) {
        $this->podcasts = $podcasts;
        $prelim_result = [];
        $c = [];
        $row = [];
        $podcast_results = [];
        foreach ($podcasts as $name => $value) {
            $params = [];
            $mysqli_stmt = $this->mysqli_obj->stmt_init();
            $sql = "SELECT item_podtype, podcast_no_item, item_title, item_description, item_guid FROM rss2_podcast_item WHERE podcast_no_item = ?";
            $mysqli_stmt->prepare($sql);
            $mysqli_stmt->bind_param('i', $value);
            $mysqli_stmt->execute();
            $meta = $mysqli_stmt->result_metadata();
            while ($field = $meta->fetch_field()) {
                $params[] = &$row[$field->name];
            }
            call_user_func_array(array($mysqli_stmt, 'bind_result'), $params);
            while ($mysqli_stmt->fetch()) {
                foreach($row as $key => $val) {
                    $c[$key] = $val;
                }
            }
            $prelim_result[] = $c;
            $mysqli_stmt->free_result();
        }
        foreach ($prelim_result as $arr) {
            foreach ($arr as $name => $value){
                $pc_result[$name] = $value;
            }
            $podcast_results[] = $pc_result;
        }
        return $podcast_results;
    }
    public function get_pc_total() {
        return $this->pc_total;
    }
}

LIST OF SUSPECT VARIABLES

$params = [];
$prelim_result = [];
$c = [];
$letter_results = [];
$next_letter_results = [];
$row = [];
$podcast_results = [];

DISCUSSION

I feel fairly comfortable with handling certain kinds of variables, but very uncomfortable handling others.  In fact, I am not at all sure why the above class works, as it took  a lot of guess work to make it function.  Guess work is inefficient.

QUESTION:  How does one properly declare class variables that are not related to the arguments of the constructor function?  Please provide examples from the list and code provided.

Roddy

 

Share this post


Link to post
Share on other sites

If it's an actual class property variable then you declare those before the constructor along with their visibility - public, protected, or private.  If you're talking about variables that you just use locally in some function, you treat them like any other variable in any other piece of code.

Share this post


Link to post
Share on other sites

Seems odd to me that you declare all of the instance variables as public. It is more normal to make them private.

  • Like 1

Share this post


Link to post
Share on other sites
Quote

... you treat them like any other variable in any other piece of code.

JSG:  Please select one of any of the provided class functions that contain "ordinary variables" and show me how you would declare them in the context of the class provided. 

davej:  Why would you make the private and not public?

Share this post


Link to post
Share on other sites

Please select one of any of the provided class functions that contain "ordinary variables" and show me how you would declare them in the context of the class provided.

You don't have to declare variables in PHP, at least not like you do in other languages where you declare a variable as a certain type before you use it.  PHP variables only need a value if you're using them, so you can either initialize them with an initial value, like an empty array if the variable is going to be an array, or just set them to their value to start with before you refer to them elsewhere.  The only way that PHP really has to declare a variable is with the class properties.

On another note, you use a lot of code to do some simple stuff here.  One issue is that you keep referring to a variable called $row that doesn't exist.  Another issue is that it looks like you have several lines of code which include multiple loops and calls to result_metadata, fetch_field, call_user_func_array, etc, which can all be replaced by a single call to fetch_all.  I don't see why you're doing it the long way when there's a single function to do that.  It seems unnecessarily complex and time-consuming.  

Share this post


Link to post
Share on other sites

JSG:  For someone who is always asking for code, you are very reluctant to provide it. A simple example in the context of the class provided would be extremely helpful.

Roddy

Share this post


Link to post
Share on other sites

JSG:  I have never used the fetch_all( ) method in this context -- only the fetch_assoc( ) method --, and it does not work in the context provided.

Roddy

Share this post


Link to post
Share on other sites

For someone who is always asking for code, you are very reluctant to provide it. A simple example in the context of the class provided would be extremely helpful.

I don't know what you're asking for.  Like I said, variables do not get declared in PHP, only defined and used, and I don't see any issues in your code other than what I described above.  The only edit I would make would be to remove the loops and fetch the result set all at once with the built-in methods.  e.g.:

$sql = "SELECT letter_no, letter_title, letter_abstract FROM sevengates_letter WHERE letter_no = ?";
$mysqli_stmt = $this->mysqli_obj->stmt_init();
$mysqli_stmt->prepare($sql);
$mysqli_stmt->bind_param('i', $next_letter_no);
$mysqli_stmt->execute();
$result = $mysqli_stmt->get_result();
$return = $result->fetch_all(MYSQLI_ASSOC);

Now $return has the entire result set, organized as an associative array.  You don't need to use a single loop.  Although it would be good practice to add error checking to that code as well.

Share this post


Link to post
Share on other sites
4 hours ago, iwato said:

Davej:  Why would you make the private and not public?

Instance variables are usually declared as private because OOP considers "encapsulation" to be a good thing. This is the same reasoning behind minimizing the number of global variables. If some variable does not need to be public or global then it shouldn't be. In your example the constructor sets the values of the instance variables, so they themselves don't need to be public.

  • Thanks 1

Share this post


Link to post
Share on other sites

Unfortunately, the following did not work.

$sql = "SELECT letter_no, letter_title, letter_abstract FROM sevengates_letter WHERE letter_no = ?";
$mysqli_stmt = $this->mysqli_obj->stmt_init();
$mysqli_stmt->prepare($sql);
$mysqli_stmt->bind_param('i', $next_letter_no);
$mysqli_stmt->execute();
$result = $mysqli_stmt->get_result();
$return = $result->fetch_all(MYSQLI_ASSOC);

I have set it aside, however, for future consideration.  I simple have no more time, if I am to meet my spring deadline for the commencement of podcast production.  I have only two major tasks left -- both of which I suspect will be far smaller than they appear daunting.  Thanks to you and others I now feel confident that I will be able to avoid many of the pitfalls into which I have fallen along the way.  Have a great week!

Roddy

Share this post


Link to post
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

×