How to use classes and constructors in PHP?

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

radulescuiulia
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Feb 23, 2013 6:42 am

How to use classes and constructors in PHP?

Postby radulescuiulia » Sat Feb 23, 2013 8:36 am

Hello!

I'm writing the following code, which doesn't print anything:

Code: Select all

class MyClass {
         private $id;
         public $string = "iiii";

         public function display () {
               echo $string;
            }
      }

   $b = new MyClass();
   $b->display();


When I replace echo $string with echo "ok", it prints "ok".
Where is the error? :help: :help: :help:

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: How to use classes and constructors in PHP?

Postby seandisanti » Mon Feb 25, 2013 9:42 am

$string does not exist in the scope of the function trying to display it. it must be referenced with $this->string


Return to “PHP coding => General”

Who is online

Users browsing this forum: Exabot [Bot] and 1 guest

cron