Methods are class-specific functions. Individual
actions that an object will be able to perform are defined within the
class as methods.For instance, to create methods that would set and get the value of the class property
$prop1, add the following to your code: Note — OOP allows objects to reference themselves using<?phpclassMyClass{public$prop1="I'm a class property!";publicfunctionsetProperty($newval){$this->prop1 =$newval;}publicfunctiongetProperty(){return$this->prop1 ."<br />";}}$obj=newMyClass;echo$obj->prop1;?>
$this. When working within a method, use $this in the same way you would use the object name outside the class.To use these methods, call them just like regular functions, but first, reference the object they belong to. Read the property from
MyClass, change its value, and read it out again by making the modifications below:<?phpclassMyClass{public$prop1="I'm a class property!";publicfunctionsetProperty($newval){$this->prop1 =$newval;}publicfunctiongetProperty(){return$this->prop1 ."<br />";}}$obj=newMyClass;echo$obj->getProperty();// Get the property value$obj->setProperty("I'm a new property value!");// Set a new oneecho$obj->getProperty();// Read it out again to show the change?>
Reload your browser, and you'll see the following:I'm aclassproperty!I'm anewproperty value!
"The power of OOP becomes apparent when using multiple instances of the
same class."<?phpclassMyClass{public$prop1="I'm a class property!";publicfunctionsetProperty($newval){$this->prop1 =$newval;}publicfunctiongetProperty(){return$this->prop1 ."<br />";}}// Create two objects$obj=newMyClass;$obj2=newMyClass;// Get the value of $prop1 from both objectsecho$obj->getProperty();echo$obj2->getProperty();// Set new values for both objects$obj->setProperty("I'm a new property value!");$obj2->setProperty("I belong to the second instance!");// Output both objects' $prop1 valueecho$obj->getProperty();echo$obj2->getProperty();?>
When you load the results in your browser, they read as follows:I'm aclassproperty!I'm aclassproperty!I'm anewproperty value!I belong to the second instance!
As you can see, OOP keeps objects as separate entities, which makes for easy separation of different pieces of code into small, related bundles.
Post a Comment
Silahkan anda tulis komentar di bawah ini !