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 Structure and the Treatment of Parameter Values

Recommended Posts

iwato    6

BACKGROUND:  Please find below a portion of a PHP class used to create an RSS feed.  Included are only the constructor function and the function used to create the actual document.  All other functions have been omitted so as to focus on the question at hand.  My reason for posting this code is to better understand the proper way to create a class.

As you can readily see from the __construct( ) function of this class each new instance of the class requires six parameter values. Although the author lists these parameters at the beginning of the class definition, he comments them out, rather than initializing them.

QUESTION:  Is this standard practice?  What is to be gained by not declaring them outside of the __construct( ) function?  It appears to create an unnecessary repetitious use of the pseudo $this variable.

<?php
/**
 * rss_feed (simple rss 2.0 feed creator php class)
 *
 * @author     Christos Pontikis http://pontikis.net
 * @copyright  Christos Pontikis
 * @license    MIT http://opensource.org/licenses/MIT
 * @version    0.1.0 (28 July 2013)
 *
 */
class rss_feed  {
 
  /**
   * Constructor
   *
   * @param array $a_db database settings
   * @param string $xmlns XML namespace
   * @param array $a_channel channel properties
   * @param string $site_url the URL of your site
   * @param string $site_name the name of your site
   * @param bool $full_feed flag for full feed (all topic content)
   */
  public function __construct($a_db, $xmlns, $a_channel, $site_url, $site_name, $full_feed = false) {
    // initialize
    $this->db_settings = $a_db;
    $this->xmlns = ($xmlns ? ' ' . $xmlns : '');
    $this->channel_properties = $a_channel;
    $this->site_url = $site_url;
    $this->site_name = $site_name;
    $this->full_feed = $full_feed;
  }
 
  /**
   * Generate RSS 2.0 feed
   *
   * @return string RSS 2.0 xml
   */
  public function create_feed() {
 
    $xml = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
 
    $xml .= '<rss version="2.0"' . $this->xmlns . '>' . "\n";
 
    // channel required properties
    $xml .= '<channel>' . "\n";
    $xml .= '<title>' . $this->channel_properties["title"] . '</title>' . "\n";
    $xml .= '<link>' . $this->channel_properties["link"] . '</link>' . "\n";
    $xml .= '<description>' . $this->channel_properties["description"] . '</description>' . "\n";
 
    // channel optional properties
    if(array_key_exists("language", $this->channel_properties)) {
      $xml .= '<language>' . $this->channel_properties["language"] . '</language>' . "\n";
    }
    if(array_key_exists("image_title", $this->channel_properties)) {
      $xml .= '<image>' . "\n";
      $xml .= '<title>' . $this->channel_properties["image_title"] . '</title>' . "\n";
      $xml .= '<link>' . $this->channel_properties["image_link"] . '</link>' . "\n";
      $xml .= '<url>' . $this->channel_properties["image_url"] . '</url>' . "\n";
      $xml .= '</image>' . "\n";
    }
 
    // get RSS channel items
    $now =  date("YmdHis"); // get current time  // configure appropriately to your environment
    $rss_items = $this->get_feed_items($now);
 
    foreach($rss_items as $rss_item) {
      $xml .= '<item>' . "\n";
      $xml .= '<title>' . $rss_item['title'] . '</title>' . "\n";
      $xml .= '<link>' . $rss_item['link'] . '</link>' . "\n";
      $xml .= '<description>' . $rss_item['description'] . '</description>' . "\n";
      $xml .= '<pubDate>' . $rss_item['pubDate'] . '</pubDate>' . "\n";
      $xml .= '<category>' . $rss_item['category'] . '</category>' . "\n";
      $xml .= '<source>' . $rss_item['source'] . '</source>' . "\n";
 
      if($this->full_feed) {
        $xml .= '<content:encoded>' . $rss_item['content'] . '</content:encoded>' . "\n";
      }
 
      $xml .= '</item>' . "\n";
    }
 
    $xml .= '</channel>';
 
    $xml .= '</rss>';
 
    return $xml;
  }

}
?>

 

 

Share this post


Link to post
Share on other sites
Ingolme    798

What he's listing in the comment are the function parameters, not the class properties. However, he hasn't declared the class properties in the class definition. Although PHP might let that slide, it's not a good idea. You should declare class properties outside of the constructor.

For XML based applications I would recommend against using strings for it. I use DOMDocument to generate XML for me.

Share this post


Link to post
Share on other sites
iwato    6

I regret not having asked this question sooner, but when you do not know anything, you have to begin by believing in something. Then, try it out, and see if it works.  The DOMDocument class does appear to be a good deal more solid, and I will certainly make use of it in the future.  Already I have included it in my notes.

For the moment I do not have time to familiarize myself with an entirely new PHP class, and would be very happy, if I could simply improve upon what I already know within the indicated class.  I do not wish to be a bad student, but need to begin earning money quickly, else there will be nothing to support my further study and implementation.  I am dangling on a financial thread that is wearing down both my spirit and health.  Please be understanding.

Returning to the original question, however, I agree that the author has listed the function's parameters, and we appear to agree that he should have first declared these parameters as class properties.  What then would have been the proper way to reference the properties' values in the appended strings to the $xml variable?

Roddy

Share this post


Link to post
Share on other sites
Ingolme    798

Your questions seemed to be about what is a good practice. I believe that's already answered. If that code is working for you then there's no need to change it.

The properties exist in his code and are being used correctly, the only problem is that he didn't declare them, which PHP seems to allow. The constructor is creating them using the arrow "->" syntax.

The only change necessary would be to declare those properties.

class rss_feed  {
  // Declare properties here:
  private $db_settings;
  private $xmlns;
  private $channel_properties;
  private $site_url;
  private $site_name;
  private $full_feed;

  /**
   * Constructor
   *
   * @param array $a_db database settings
   * @param string $xmlns XML namespace
   * @param array $a_channel channel properties
   * @param string $site_url the URL of your site
   * @param string $site_name the name of your site
   * @param bool $full_feed flag for full feed (all topic content)
   */
  public function __construct($a_db, $xmlns, $a_channel, $site_url, $site_name, $full_feed = false) {
    // Assign to properties here:
    $this->db_settings = $a_db;
    $this->xmlns = ($xmlns ? ' ' . $xmlns : '');
    $this->channel_properties = $a_channel;
    $this->site_url = $site_url;
    $this->site_name = $site_name;
    $this->full_feed = $full_feed;
  }

 

Share this post


Link to post
Share on other sites
iwato    6

Thank you for your continued clarification.

Now, had the properties been declared, as you have just done, would it have been necessary for the author to use the arrow operator in the second function as well?  I am referring in particular to the function called create_feed( ).  As I mentioned in my original post, it appears to me that by not declaring the variables at the beginning of the class, the author has compelled an inordinate use of the arrow operator.  Is this not true?  Or, have I misunderstood?

Roddy

 

 

Share this post


Link to post
Share on other sites
Ingolme    798

None of the syntax would have to change, he's already doing everything correctly. I assume that when PHP sees an assignment to an undeclared property it creates the property, from that moment onward everything's the same as if the property had been declared.

The only thing I notice that won't work is that he's calling a method get_feed_items() which doesn't exist.

Share this post


Link to post
Share on other sites
iwato    6

The method is there.  Simply I left it out, so as not to cause unnecessary clutter. 

Maybe I have misunderstood the use of the constructor function.

Until now I was under the impression that once the values of a constructor function's parameters are assigned to the declared properties via the $this->declared_property mechanism, they can be readily accessed in other methods of the class simply by inserting their respective variable names.

By way of example consider the following line of code taken from the create_feed( ) method.

 $xml .= '<title>' . $this->channel_properties["title"] . '</title>' . "\n";

Had the property $channel_properties been properly declared at the outset of the class definition, then its elements and their respective values could have been directly accessed from within the create_feed( ) and other class methods without having to make use of the pseudo $this variable and the arrow operator?  

In other words, rather than writing the above the author could simply have written

$xml .= '<title>' . $channel_properties["title"] . '</title>' . "\n";

Am I in error in this regard?

Roddy

Share this post


Link to post
Share on other sites
Ingolme    798

PHP doesn't work that way that I can remember, that's a Java thing. You can do an experiment to confirm.

Share this post


Link to post
Share on other sites
iwato    6

Oops!  I thought someone would know this, so that I could avoid the experimentation.

Roddy

Share this post


Link to post
Share on other sites
justsomeguy    954

If you are referring to a property or method of a class, you always access it via a class or scope object ($this in the case where you are referring to a property or method inside the same non-static class).  That's how PHP knows you are referring to a class member and not a regular variable.

Share this post


Link to post
Share on other sites
iwato    6

I have never heard of a static class -- only static properties and methods of a class.  Do you mean by non-static class a class without static properties or methods?

If I have understood correctly, the purpose of the pseudo $this variable  is to distinguish between variables within a specific scope or class from regular variables -- these latter being variable that can be used anywhere except within a class or specified scope.  In effect, one can speak of three different kinds of variables:

1) regular variables -- variables defined and used outside of specific scopes and classes.

2) $this -> variables -- variables defined within a specific scope or class and  accessed from within the scope or class using the $this-> notation of from without using a class object and the -> operator.

3) global variables -- variables defined within a specific scope (not class) that can be accessed from without the scope as regular variables and presumably within the scope as same.

Is this assessment correct?  Have you anything to add?

Share this post


Link to post
Share on other sites
justsomeguy    954

Do you mean by non-static class a class without static properties or methods?

More or less.  I was saying that if you are referring to a non-static member then you use $this to refer to the instantiated object, but you don't use $this when accessing static members.

There's some information in the manual about variables in general:

http://php.net/manual/en/language.variables.php

And about classes:

http://php.net/manual/en/language.oop5.php

Particularly these parts:

http://php.net/manual/en/language.oop5.properties.php

http://php.net/manual/en/language.oop5.visibility.php

http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

Using $this is how you refer to the instantiated object inside the code for the class.  When I refer to a static class I'm talking about a class that you don't instantiate, only define.

Share this post


Link to post
Share on other sites
iwato    6

Thank you.

I will add these links to my notes.

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

×