Web Analytics Made Easy -
StatCounter Question on setting data members in class - CodingForum

Announcement

Collapse
No announcement yet.

Question on setting data members in class

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Question on setting data members in class

    Hi guys..... I know the best way to get my answer for this is to test it, but I was wondering if setting up data members via a method works/is standard?

    Normal example use of setting data members up with constructor:

    Code:
    class fooBar {
    
        var $foo;
    
        function __construct() {
            $this->foo = $foo;
        }
    
    }
    Now, will this work as well?

    Code:
    class fooBar {
    
        var $foo;
        var $bar;
    
        function __construct($foo) {
            $this->foo = $foo;
        }
    
        function check($bar) {
            $this->bar = $bar;
        }
    
    
    }
    
    $foobar = new fooBar($foo);
    $foobar->check($bar);
    Thanks!

  • #2
    Yep.
    In PHP, you don't technically need a member at all. Its not good practice IMO, but you should be able to do this:
    PHP Code:
    class MyClass
    {
        public function 
    __construct($variable)
        {
            
    $this->variable $variable;
        }
    }

    $mc = new MyClass('test'); 
    $mc will now have a public member called variable with the value of test. It is often useful to use you're constructor to call setters, depending on the handling of you're objects:
    PHP Code:
    class User
    {
        private 
    $sName;
        public function 
    __construct($sName)
        {
            
    $this->setName($sName);
        }

        public function 
    setName($sName)
        {
            
    $sName trim($sName);
            if (empty(
    $sName))
            {
                throw new 
    InvalidArgumentException('Name cannot be empty!');
            }
            
    $this->sName $sName;
        }
    }

    try
    {
        
    $u1 = new User('Fou-Lu'); // Ok, $u1 has a name of Fou-Lu
        
    $u2 = new User(''); // Throws InvalidArgumentException
    }
    catch (
    InvalidArgumentException $ex)
    {
        print 
    $ex->getMessage();

    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

    Comment


    • #3
      Thanks for the info Fou-Lou..... I will see if this helps me any in what I'm trying to do.

      Comment

      Working...
      X