Log in / create account | Login with OpenID
DocForge
An Open Wiki For Software Developers

Method

From DocForge

A method is a function defined within a class. While properties represent the state of an object, methods define the actions which can be performed by the object, often altering the state.

Scope [edit]

A private method is only available to other methods within the class. A protected method is available to other methods within the class and any classes which extend it. A public method can be called from outside or inside the class.

A static method is not tied to the instance of the object. It therefore doesn't have direct access to any non-static properties of its class.

Examples [edit]

PHP:

class Address {
    // Properties
    private $city;
    private $state;
    private $zip;
 
    // Private method not accessible outside this class
    private function set_zip($new_zip) {
        $this->zip = $new_zip;
    }
 
    // Public methods can be called from outside this class
    public function get_zip() {
        return $this->zip;
    }
}
 
$address = new Address();
echo $address->get_zip();    // Will return the address's zip property value
echo $address->set_zip('12345');    // Will fail because set_zip is a private method

See Also [edit]