Results 1 to 4 of 4

Thread: get and set methods

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2007
    Location
    Karachi
    Posts
    551

    get and set methods


    Hello every one!

    does any one have nay idea that is there any get and set method in php like we have in following C#

    public int ProductID
    {
    get
    {
    return intProductID;
    }
    set
    {
    intProductID=value;
    }
    }


    so does any one have knowldege how to make a class where i write

    my code in php like above manner

    Hope any one would reply me

  2. #2
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: get and set methods

    The usual way is to use two methods: getProductID and setProductID. This avoids confusion as it is obvious that a method is being called rather than a field being read/set directly.
    If there is nothing special that should be done when assigning or reading a property then you should just make the field public.

    You can also use the magic methods __get and __set. These are not quite as nice as the property syntax in .NET as you have to place all of the logic for every property into the two methods. When using this approach it is simplest to store all of the properties in a private array.
    PHP Code:
    class PropertyExample
    {
      private 
    $_properties = array();

      public function 
    __get($prop)
      {
        return 
    $this->_properties[$prop];
      }

      public function 
    __set($prop$val)
      {
        
    $this->_properties[$prop] = $val;
      }


  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2007
    Location
    Karachi
    Posts
    551

    Re: get and set methods


    and how to make object of this class and use these proeprties(get and set)

  4. #4
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: get and set methods

    Just like C#


    PHP Code:
    $myobj = new MyClass();

    $myobj->myprop somevalue;
    echo 
    $myobj->myprop

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width