Jump to content

Properties and their use in Methods


l33t fl33t

Recommended Posts

I've switched to OOP only recently and am having trouble with a piece of code I'm using. I don't know why the following code doesn't output anything, not even an error. And yes, the properties/method need to be defined like this rather than the function($bir='win') way. So - the question is - how do I get the method to recognize the properties.

 

class test
{	public $bir='win';
public $wind='th';
public function test(){

	echo $wind.$bir;}
}
$obj = new test();

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/109457-properties-and-their-use-in-methods/
Share on other sites

Yay, it works now. Can you also change the properties from outside the class?

 

EDIT: Nevermind, found a way. Mind explaining me what's the trick in $this-> and why is it needed?

 

The 'this' keyword refers to the current instantiated object.  An example (using PHP 5 syntax):

<?php
   class Example
   {
      private $myProp;

      public function __construct($input = null) //we set a default value for $input in case the user doesn't want to instantiate the object with its property already set
      {
         $this->myProp = $input;
      }

      public function setProp($input) //explicit method to set the property
      {
         $this->myProp = $input;
      }

      public function getProp() //method to retrieve the property
      {
         return $this->myProp;
      }
   }

   $obj1 = new Example();
   $obj1->setProp("This is Example 1");

   $obj2 = new Example("This is Example 2");

   echo "Example 1: {$obj1->getProp()} -- Example 2: {$obj->getProp()}";
   //should output:
   //Example 1: This is Example 1 -- Example 2: This is Example 2
?>

 

So, as you can see, the 'this' keyword refers to the current object.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.