Jump to content

Recommended Posts

Posted

One way in which our TextBox class is not very useful is that its instances do not contain any data when they are created, except for the static initialization of the variable $body_text.

The point of such a class would be to display arbitrary pieces of text, not the same message every time. It's true that we could make an instance and then install the right data in the instance's internal variables, like so:

$box=new TextBoxSimple;

$box->body_text="custom text";

$box->display();
The correct way to arrange for data to be appropriately initialized is by writting a constructor function- a special function called__construct(), which will be called automatically whenever a new instance is created. Example:
?php


class TextBox{

var $body_text="my text";

//constructor function

function__construct($text_in)

{

$this->body_text=$text_in;

}

function display()

{

print("<table border=1><tr><td>$this->body_text");

print("</td></tr></table>");

}

}

//creating an instance

$box=new TextBox("custom text");

$box->display();

As the preceding code is executed, the output is an HTML table enclosing the text "custom text".

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • 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.