Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.