note 108744 deleted from language.oop5 by bjori
| From: | bjori@php.net | Date: | Wed, 18 Jul 2012 16:28:54 +0000 |
| Subject: | note 108744 deleted from language.oop5 by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189283@lists.php.net to get a copy of this message | ||
Note Submitter: wbcarts at juno dot com
----
PHP Class TERMINOLOGY
If you find that your code lacks structure, organization, and/or is hard to maintain... PHP Classes
may be what you need. But first, some terminology -- terms are in UPPERCASE:
<?php
class MyClass
{
// This is the CLASS DEFINITION (everything in the curly brackets).
// $myVar is DECLARED, but it is not INITIALIZED (assigned a value).
protected $myVar;
public function __construct($value = 'What?')
{
$this->setMyVar($value); // $myVar will now be INITIALIZED
}
public function setMyVar($value)
{
if(!is_string($value))
{
$value = (string)'Non-String type passed in argument';
}
$this->myVar = $value;
}
}
?>
The class definition is like a blueprint. Imagine an architect who goes to the job site carrying a
big roll of papers with drawings on them. Those drawings represent a design which is meant 'to
be built', and they are used throughout the entire construction process. Once the project is
done, then people occupy the buliding and commense their work. One crucial difference between a
CLASS DEFINITION and a blueprint though is, that a class definition does say what does and what
doesn't go on with the project after it is designed and built.
We have a CLASS DEFINITON at this stage -- PHP is happy -- but it does nothing for us yet. We need
to INSTANTIATE (make real MyClass object(s)) and have those INSTANCE(S) follow the design and rules
outlined in the CLASS DEFINITION.
<?php
// INSTANTIATE (to build or create) objects with the 'new' operator.
$mc1 = new MyClass(); // $mc1 is now an INSTANCE (built or created, materialized).
$mc2 = new MyClass('Hello World'); // $mc2 is now an INSTANCE (built or created,
materialized).
$mc3 = new MyClass('Take that!'); // $mc3 is now an INSTANCE (built or created,
materialized).
$mc4 = new MyClass(true); // $mc4 is now an INSTANCE (built or created, materialized).
?>
Now it is time to put the INSTANCES to work. According to our CLASS DEFINITION, all we can do is set
the value of $myVar with the setMyVar() function.
<?php
$mc1->setMyVar(''); // Ok
$mc2->setMyVar(''); // Ok
$mc3->setMyVar(''); // Ok
$mc4->setMyVar(''); // Ok
?>
Try putting a non INSTANCE to work:
<?php
$youTrickyLittleBitch->setMyVar('You like that?');
?>
That throws: 'Fatal error: Call to a member function setMyVar() on a non-object'. This
means that the variable was not INSTANTIATED with the proper CLASS DEFINITON, therefore it is not an
INSTANCE of that class, therefore illegal to even try.