/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] PHP Class Files

noob to oop and starting to create php class files, i have a couple of questions:

1- When should i declare variables in the class file (i,e, varable $result)? I have written a couple of quite complex class fiels that use variables that I have not explicitly declared at the start of the class definition but seem to work quite well. Is it going to cause me problems later?

2 – To avoid complex if .. then … else statements, is it possible to use a break/exit type command to end the function (in particular a constructor) when a condition is satisfied? Currently my latest class file to integrate paypal PDT processing has 16 nested if/else statements and whilst it works I just feel it is not as efficient as it could be. All my attempts to use break/exit end the php script that is calling the class/function.

thanks
Graham

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@NogDogFeb 09.2009 — 
  • 1. If you are referring to class variables (as opposed to variables that are internal only to a class method), if you do not declare it then (a) you cannot control its visibility via the public/protected/private keywords, and (b) it is not a visible part of the class interface, making it more difficult to use or maintain the class.


  • 2. Complex if/elseif/else or switch structures in a class almost always indicate that the class is trying to do too much and should be broken up: either into separate, more focused classes or else via inheritance into child classes of a parent, possibly abstract, class.


  • I would strongly recommend Matt Zandstra's [i][url=http://www.apress.com/book/view/9781590599099]PHP Objects, Patterns, and Practice[/url][/i] to help understand OOP in PHP (at least it did a lot to help me "get it").
    Copy linkTweet thisAlerts:
    @MindzaiFeb 09.2009 — To add to NogDog's comments, if you want to 'end' a method when a certain condition is satisfied, you can just return; like a normal function.

    As mentioned though, it's much better to break things down into small, manageable methods - thats what classes are for after all. Each method should do just one thing. Most of my methods are no more than a few lines, and very focused on one task. This makes reading, debugging and modifying code all so much easier.
    Copy linkTweet thisAlerts:
    @NogDogFeb 10.2009 — Since I'm still waiting for a client to get back to me with info so I can keep working (:rolleyes?, here's a simplistic example to illustrate how you can break out functionality into separate classes. In this case it illustrates the "Strategy Pattern" where the different strategies are sub-classes of an abstract pattern, and which strategy to use is chosen when the main object which utilizes the strategy is instantiated.
    [code=php]
    <?php
    /**
    * Main class
    **/
    class Example
    {
    private $calculator;
    private $values = array('foo' => 0, 'bar' => 0);

    public function __construct(Calculator $calculator)
    {
    $this->calculator = $calculator;
    }

    public function __set($key, $value)
    {
    if(isset($this->values[$key]))
    {
    $this->values[$key] = $value;
    return true;
    }
    return false;
    }

    public function result()
    {
    return($this->calculator->calculate($this->values['foo'], $this->values['bar']));
    }
    }

    /**
    * Here we define our various calculator strategies
    **/

    /**
    * This defines our abstract interface
    **/
    abstract class Calculator
    {
    public abstract function calculate($value1, $value2);
    }

    /**
    * Addition strategy
    **/
    class AddCalculator extends Calculator
    {
    public function calculate($value1, $value2)
    {
    return $value1 + $value2;
    }
    }

    /**
    * Subtraction strategy
    **/
    class SubtractCalculator extends Calculator
    {
    public function calculate($value1, $value2)
    {
    return $value1 - $value2;
    }
    }

    // SAMPLE USAGE:

    $test = new Example(new SubtractCalculator());
    $test->foo = 10;
    $test->bar = 7;
    echo $test->result(); // "3"
    [/code]

    You could get the same functionality in one class, but you start getting into the "ugliness" of conditional statements, and the need to have to edit multiple parts of the class if you want to add new strategies (e.g. multiply and divide calculations):
    [code=php]
    <?php
    /**
    * Main class
    **/
    class Example
    {
    private $strategy;
    private $values = array('foo' => 0, 'bar' => 0);

    public function __construct($strategy)
    {
    // Because we can't type-hint, we have to add error-checking.
    // This error-checking would have to change if we wanted to add a strategy
    if(!in_array($strategy, array('add', 'subtract')))
    {
    throw new Exception("Invalid strategy '$strategy'");
    }
    $this->strategy = $strategy;
    }

    public function __set($key, $value)
    {
    if(isset($this->values[$key]))
    {
    $this->values[$key] = $value;
    return true;
    }
    return false;
    }

    public function result()
    {
    // now we are forced to use some sort of conditional logic
    // if we want to add a new strategy, then we have to modify this code, too
    switch($this->strategy)
    {
    case 'add':
    return $this->values['foo'] + $this->values['bar'];
    break;
    case 'subtract':
    return $this->values['foo'] - $this->values['bar'];
    break;
    default:
    user_error("How did we get here?", E_USER_ERROR);
    }
    }
    }

    // SAMPLE USAGE:

    $test = new Example('add');
    $test->foo = 10;
    $test->bar = 7;
    echo $test->result(); // "17"
    [/code]
    Copy linkTweet thisAlerts:
    @the-ferretauthorFeb 10.2009 — Thanks for the advice guys.
    ×

    Success!

    Help @the-ferret spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.28,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...