I'm a bit lost here because I want to do something that is very easy in Java but seems a bit complicated in PHP.
We are building an SDK for our product and in Java, we have this one class that must not (!) be instantiated by the user (i.e. the coder), since there are several constraints regarding it's integrity. So we've built that as a nested class "X" inside of the "XFactory" and you will get an instance of X by calling XFactory.buildMeMyX(); - Easy...
Now PHP does not support nested classes at all, and I wonder how to apply the same here. In Java, X's constructor is hidden (private), so only XFactory can call it.
In PHP, it looks like I will have to make __construct() public and move the nested class X out of XFactory. Hence, the user will be able to create an instance without the Factory.
Now - I COULD move the factory functionality to X itself and move all the stuff there, but this would kind of break the design of the SDK. Is there a useful way to do such things in PHP after all?
For PHP 5.x you already described your options, there are no private/protected classes or inner classes at all, so there is no further way to restrict instantiation.
However, with PHP 7 this is going to change.
There are still no nested classes (although we might get them in the future, see: https://stackoverflow.com/a/31454435/664108), but you could instantiate an anonymous class and only provide the consumer with its interface like this:
class XFactory
{
public function buildMeMyX()
{
return new class() implements XInterface {
public function doWhatEverAnXCanDo()
{
// X X X
}
// ...
};
}
}
interface XInterface
{
function doWhatEverAnXCanDo();
}
As the others have said, there currently is no clean way to implement this behavior in PHP. In my opinion, the only valid use case for private constructors are factories inside the class that implement that factories.
Whenever you try to get around that use case it gets messy. No one should ever try to invent clever ways to bypass PHP's language limiations.
I just violated that rule by myself just to prove it is indeed possible. But please refrain from using that in production, or better: using it anywhere. I will try to find some bulletproof arguments for that suggestion and edit the answer afterwards.
<?php
class Dependency {}
class SomeClass {
protected $dep;
private function __construct(Dependency $dep)
{
$this->dep = $dep;
}
public function doSomething()
{
var_dump($this->dep);
echo "Doing Stuff and even having dependencies";
}
}
class SomeClassFactory {
public function buildSomeClass()
{
return $this->instantiateSomeClassWith(new Dependency);
}
protected function instantiateSomeClassWith()
{
$reflectionClass = new ReflectionClass('SomeClass');
$someClass = $reflectionClass->newInstanceWithoutConstructor();
$constructor = $reflectionClass->getConstructor();
$constructorClosure = $constructor->getClosure($someClass);
call_user_func_array($constructorClosure, func_get_args());
return $someClass;
}
}
$factory = new SomeClassFactory();
$someClass = $factory->buildSomeClass();
$someClass->doSomething();
?>
Output: object(Dependency)#2 (0) { } Doing Stuff and even having dependencies
The theory is simple. The constructor of the class that will be built via the Factory is made private. We make use of reflection within the factory to create an instance of the class without invoking the constructor.
Once we have an instance, we grab the closure of the constructor and invoke it via call_user_func_array(). That way you can make use of Dependency Injection just as you would if the constructor was public.
As I said before. That way is a single smell. By creating an object without invoking it's constructor, there is no real way to validate an objects state upon creation
This is a proof of concept, but the concept sucks.
There is no native way to do so, yet. However, if you really want to "enforce" that your class is only created from your factory class, there is a little "hackish" way to do so limiting the instantiation by inistantiating class.
class X
{
function __construct()
{
new Y();
}
}
class Y
{
function __construct()
{
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
if (!isset($trace[1]['object']) || !($trace[1]['object'] instanceof X)) {
throw new \RuntimeException('This is a private class');
}
}
}
new X(); // All is fine
new Y(); // Exception
Please note that there is no "real" way to protect the class from being instantiated from elsewhere even using this approach - it still can be done via reflection by bypassing the constructor, or simply modifying your source.
I've recently read that using the keyword "new" in a constructor is highly frowned upon, but I'm not sure I understand why? For example, how is:
class A {
public $foo;
function __construct() {
$this->foo = new Bar();
}
}
Any different from:
class A {
public function someMethod() {
$foo = new Bar();
}
}
???
This is really the theory behind dependency injection.
It's not that using "new" is a bad idea, per se. Rather, by instantiating objects inside of your class your are creating hard dependencies which can never be changed or switched out without changing the class itself.
It also violates the paradigm of "coding to interface, not implementation"
Example:
class Phone {
protected $network;
public function __construct() {
$this->network = new Verizon();
$this->network->distinctiveRing();
}
}
class Verizon {
public function call($number) {
....
}
public function distinctiveRing() {
}
}
Now, suppose one day you wanted to create an ATT, TMobile and Sprint phone? Surely they are all able to make calls, and can do so having just a phone number. Also, the phone class shouldn't care who the carrier is, as it's job is to facilitate entering a number - not to actually make a network connection, right?
So, that being said, we shouldn't have to create a new SprintPhone class that can instantiate another Sprint network object, right? Right.
So what's the better way?
class Phone {
protected $network;
public function __construct(NetworkInterface $network) {
$this->network = $network;
}
}
interface NetworkInterface {
public function call($number);
}
class Verizon implements NetworkInterface {
...
}
class Sprint implements NetworkInterface {
...
}
Well now, you can just say: $phone = new Phone(new Sprint()) or $phone = new Phone(new Verizon())
Also notice that our call to distinctiveRing is gone. Why? Well, because we don't know that any object implementing NetworkInterface will necessarily support a distinctive ring. But this is good because now our Phone can support ANY Network with no code changes.
If you want support for distinctive ring, you can always create a new interface that supports the distinctiveRing method. In your Phone object, you can check if your Network implements DistinctiveRingerInterface and, if so, make your distinctive ring. But you're no longer tied to a specific network with this approach. Better yet, you were forced to do this because you took the right approach from the start.
And, any other network which can feasibly be created later down the road. More importantly, your class no longer has to care about what kind of Network object it's given. It knows, (because it received an object implementing NetworkInterface), that the Network object is able to make a call with a $number.
This also tends to lead to much better code, with a better separation of concerns.
And finally: testing.
With the first example, if you tried to test your Phone object, it was going to make a call on the Verizon network. Sucks to be the person getting called all day because you're running unit tests, right? Right.
Well, simply create a TestNetwork class that implements NetworkInterface, and pass that to your phone object. Your TestNetwork class can do anything you want inside of it's call method - or do nothing.
Furthermore, you can just create a mock object using PHPUnit, and ensure that the call method on your TestNetwork actually gets called. You couldn't do this before because the Network was being instantiated inside of your Phone.
It seems that your question and your code example do not share too much?
Your first code sample should work, because you assign to a class variable:
class A {
public $foo;
function __construct() {
$this->foo = new Bar();
}
}
Your second sample assigns it to a variable local to the __construct() method, so you will have no chance of retrieving the value later on:
class A {
public function someMethod() {
$foo = new Bar();
}
}
Besides: Using new is usually fine. However, you might have read about inversion of control or IOC which is a technique to avoid having dependencies and so you would try to avoid the creation of classes directly in the constructor, see for example http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php
In first example $foo is available in any method in this class and also outside the object
so you can do:
$a = new A();
$a->foo->sth;
In second example $foo is available only inside someMethod.
I was trying to find a way to execute some code to alter the results of an objects methods without actually touching the object's code. One way I came up is using a decorator:
class Decorator {
private $object;
public function __construct($object) {
if (!is_object($object)) {
throw new Exception("Not an object");
}
$this->object = $object;
}
protected function doSomething(&$val) {
$val .= "!!";
}
public function __call($name, $arguments) {
$retVal = call_user_func_array(array($this->object, $name), $arguments);
$this->doSomething($retVal);
return $retVal;
}
}
class Test extends BaseTest {
public function run() {
return "Test->run()";
}
}
$o = new Decorator(new Test());
$o->run();
That way it will work properly but it has one disadvantage which makes it unusable for me right now - it would require replacing all lines with new Test() with new Decorator(new Test()) and this is exactly what I would like to avoid - lots of meddling with the existing code. Maybe something I could do in the base class?
One does not simply overload stuff in PHP. So what you want cannot be done. But the fact that you are in trouble now is a big tell your design is flawed. Or if it is not your code design the code you have to work with (I feel your pain).
If you cannot do what you want to do it is because you have tightly coupled your code. I.e. you make use of the new keyword in classes instead of injecting them (dependency injection) into the classes / methods that need it.
Besides not being able to easily swap classes you would also have a gard time easily testing your units because of the tight coupling.
UPDATE
For completeness (for possible future readers): if the specific class would have been namespaced and you were allowed to change the namespace you could have thought about changing the namespace. However this is not really good practice, because it may screw with for example autoloaders. An example of this would be PSR-0. But considering you cannot do this either way I don't see it is possible what you want. P.S. you should not really use this "solution".
UPDATE2
It looks like there has been some overload extension at some time (way way way back), but the only thing I have found about it is some bug report. And don't count on it still working now either way. ;-) There simply is no real overloading in PHP.
Found something (a dead project which doesn't work anymore that enables class overloading): http://pecl.php.net/package/runkit
Possibly another project (also dead of course): http://pecl.php.net/package/apd
I am not a PHP programmer, but I think that AOP is what you are looking for. You can try some frameworks, for example listed in this answer.
From the Wikipedia article on the decorator pattern:
Subclass the original "Decorator" class into a "Component" class
So I think you're supposed to keep the class to be decorated private and expose only the already-decorated class.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Could this be classified as correct OOP programming?
class Greeting {
public $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
function __construct($name) {
$this->name = $name;
shuffle($this->greet);
}
}
$hi = new Greeting('INSERTNAMEHERE'); /*NAME OF PERSON GOES HERE*/
echo $hi->greet[1] .' '. $hi->name;
For the sake of Keeping it Simple, I'd say it's okay. It's not too proper OOP though, nor is it particularly easy to understand code. Having working code is better than having no code at all though.
Let's go through your code:
1 class Greeting {
2
3 public $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
4
5 function __construct($name) {
6 $this->name = $name;
7 shuffle($this->greet);
8 }
9 }
Line 1: says this class represents the concept of a Greeting. What is a Greeting? I'd say something like "Hello John" or "Hi John" or "Howdy John" is a greeting. And in fact, you seem to agree because in …
Line 3: … you do have a list of similar greetings, just without a name. But that property warrants the question why your class is named Greeting, when it really encapsulates multiple greetings already. Shouldn't the class be called Greetings (mind the plural) then?
Line 3: Naming the property "greet" wasn't a too good idea either. It's a property, so dont give it the name of a verb. Verbs are for methods.
Line 3: Although there is people who will tell you different, making the property public is rarely a good idea. Properties are about internal state and that state should not be accessible directly, but only through methods.
Line 5: Your constructor then tells me a Greeting has to have a name. If I wouldn't be looking at the source code already, I'd falsely assume this to be the name of the Greeting. But you really mean a Person's name. The argument should reflect that and be named something more indicative, like $greetedPersonsName.
Line 6: Assigning properties on the fly is a boo boo. If I look at the class definition, I want to see the properties immediately. Discovering them inside some method makes the code hard to understand. This will also not getting picked up when generating API docs. Avoid it.
Line 7: The shuffle is another unexpected thing. It's a non-obvious side-effect. If I was to instantiate a new Greeting, I'd expect the greetings to appear in the order they are listed. It's against the Principle of Least Astonishement to shuffle them in the ctor. The shuffling should happen from a public method that does nothing but shuffling, e.g.
public function shuffleGreetings()
{
shuffle($this->greetings);
}
Assuming the idea of the class was really to be a single Greeting that just initializes itself with one of the default possible values, we can also add a Getter like this:
public function getGreeting()
{
return $this->_greetings[0] . ' ' . $this->name;
}
This is better than doing
echo $hi->greet[1] .' '. $hi->name;
because it hides the implementation details. I don't need to know that the Greeting object has an array of possible greetings. I just want to get the Greeting combined with the set name. It's still far from perfect though, because you still would use it like
$hi = new Greeting('John'); // A Greeting named John? Why $hi then?
$hi->shuffleGreetings(); // Shuffling Greetings in a Greeting?
echo $hi->getGreeting(); // Why is it "Hello John" all of a sudden?
As you can see, the API is still pretty much full of WTF. A developer will still have to look at your source code to understand what's going on.
More on Side-Effects
While it may be tempting to put the shuffle into getGreeting you should not do so. A method should return the same thing for the same input. When I call getGreeting twice in a row, I can expect it to return the same result. You would expect 1+1 to return 2 always, so make sure your methods do too.
Likewise, if you want to have a single method to return a random item from the greetings property, dont shuffle the greetings array. If you would use the shuffle method instead, you would also change the greetings property. That ripples to any function reading from the property, e.g. when you do
public function getRandomGreeting()
{
$this->shuffleGreetings();
return $this->getGreeting();
}
a developer will experience something like this:
$hi = new Greeting('John');
$hi->shuffleGreetings();
echo $hi->getGreeting(); // for example "Hello John"
echo $hi->getRandomGreeting(); // for example "Hi John"
echo $hi->getGreeting(); // for example "Howdy John" <-- WTF!!
Use an implementation that doesnt change the property, e.g.
public function getRandomGreeting()
{
$randomKey = array_rand($this->greetings);
return $this->greetings[$randomKey] . ' ' . $this->name;
}
That is free of side-effects:
$hi = new Greeting('John');
$hi->shuffleGreetings();
echo $hi->getGreeting(); // for example "Hello John"
echo $hi->getRandomGreeting(); // for example "Hi John"
echo $hi->getGreeting(); // still "Hello John". Expected!
The API is still far from pretty though. If I think about the properties of a Greeting, I just dont think "Person's name". Just saying "Hi" oder "Hello" is still a valid greeting. It doesn't require a name. How about
public function greetPerson($personName)
{
return $this->getGreeting() . ' ' . $personName;
}
and then we can do
$hi = new Greeting;
$hi->shuffleGreetings();
echo $hi->greetPerson('John');
And to finally hide that our Greeting contains an array that needs to be shuffled, let's move our shuffleGreetings method back to the ctor and rename the class to RandomGreeting.
class RandomGreeting …
public function __construct()
{
$this->shuffleGreetings();
}
This might seem counterintuitive at first, because I told you not to shuffle in the ctor. But with the class renamed to RandomGreeting, it is much more to be expected that there is something happening behind the scenes. We just don't need to know what exactly. To reflect that, we should also make the shuffleGreetings method protected now. We just hide it from the public interface completely. Now our code reads like this:
$hi = new RandomGreeting;
echo $hi->greetPerson('John'); // ex "Howdy John"
This doesn't give you any WTFs because your code clearly communicates you'll get a random greeting. The classname clearly communicates what it does.
This is a little bet better now and we could end here, but one could still argue that a Greeting should not be able to greet on it's own, but is rather something that is done by a Person instead.
Improving it
Our findings should lead us to the conclusion that a Greeting should rather be a dumb Type encapsulating the Greeting message and nothing else. All it should do is return that message. Since the Greeting doesn't have any real behavior next to storing the message string, the easiest would be to create a Value Object, e.g. an object that is equal to another object by value of a property:
class Greeting
{
protected $value;
public function __construct($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
The other way to do it would be to make the various available greetings into separate types. There is very little gain to do that when your objects don't have behavior. You only need that if you want to take advantage of Polymorphism. However, having concrete subtypes does draw a few additional things to consider later on, so let's just assume we need it.
The proper way to do that in OOP would be to define an interface
interface Greeting
{
public function getGreeting();
}
that defines a class that wants to behave like a Greeting has to have a getGreeting method. Since interfaces dont implement any logic, we also add an abstract type that contains the greeting property and the logic to return it:
abstract class GreetingType implements Greeting
{
protected $greeting;
public function getGreeting()
{
return $this->greeting;
}
}
When there is an abstract class, there also needs to be concrete classes derived from the abstract class. So let's use Inheritance to define our concrete Greeting types:
class HiGreeting extends GreetingType
{
protected $greeting = 'Hi';
}
class HelloGreeting extends GreetingType
{
protected $greeting = 'Hello';
}
class HowdyGreeting extends GreetingType
{
protected $greeting = 'Howdy';
}
It's not absolutely necessary to have an Interface and an Abstract implementing the interface. We could have made our concrete Greetings not extend from the GreetingType. But if we had just reimplemented the getGreeting method on all the various Greeting classes, we would be duplicating code and were much more prone to introducing errors and should we ever need to change something, we'd have to touch all these classes. With the GreetingType it's all centralized.
The other way round is true as well. You dont necessarily need an interface. We could have used just the abstract type. But then we would be limited to the GreetingType whereas with an interface, we could potentially add new Types with much more ease. I admit I can't think of any right now, so it is probably YAGNI. But it's so little to add that we can just as well keep it now.
We will also add a Null Object that returns an empty string. More on that later.
class NullGreeting extends GreetingType
{
protected $greeting = '';
}
Object creation
Because I do not want to litter new classname all over my consuming classes and introduce coupling, I will a use simple Factory instead to capsule object creation:
class GreetingFactory
{
public function createGreeting($typeName = NULL)
{
switch(strtolower($typeName)) {
case 'hi': return new HiGreeting;
case 'howdy': return new HowdyGreeting;
case 'hello': return new HelloGreeting;
default: return new NullGreeting;
}
}
}
The Factory is one of the few pieces of code where you actually can use a swich/case without having to check if you can Replace Conditional with Polymorphism.
Responsibility
With object creation out of the way, we can finally start to add our Greetings class:
class Greetings
{
protected $greetings;
protected $nullGreeting;
public function __construct(NullGreeting $nullGreeting)
{
$this->greetings = new ArrayObject;
$this->nullGreeting = $nullGreeting;
}
public function addGreeting(Greeting $greetingToAdd)
{
$this->greetings->append($greetingToAdd);
}
public function getRandomGreeting()
{
if ($this->hasGreetings()) {
return $this->_getRandomGreeting();
} else {
return $this->nullGreeting;
}
}
public function hasGreetings()
{
return count($this->greetings);
}
protected function _getRandomGreeting()
{
return $this->greetings->offsetGet(
rand(0, $this->greetings->count() - 1)
);
}
}
As you can see, Greetings is really just a wrapper for an ArrayObject. It makes sure that we cannot add anything else but objects implementing the Greeting interface to the collection. And it also allows us to pick a random Greeting from the collection. It also makes sure that you always get a Greeting from the call to getRandomGreeting by returning the NullGreeting. This is awesome, because without that you would have to do
$greeting = $greetings->getRandomGreeting();
if(NULL !== $greeting) {
echo $greeting->getMessage();
}
in order to avoid a "Fatal Error: Trying to call method on non-object" when the getRandomGreeting method did not return a Greeting object (when there is no Greeting in the Greetings class yet).
The class has no other responsibility than that. If you are unsure if your class is doing too much or has methods that should better be on some other object, look at the methods in that class. Do they work with a property of that class? If not, you should probably move that method.
Getting it done
Now to finally put all that code to use, we add our Person class now. Since we want to make sure we can call a getName method on it, we create an interface before doing so
interface Named
{
public function getName();
}
We could have named that interface IPerson or whatever but it only has one method getName and the most fitting name is Named then, because any class implementing that interface is a named thing, including, but not limited to our Person class:
class Person implements Named
{
protected $name;
protected $greeting;
public function __construct($name, Greeting $greeting)
{
$this->name = $name;
$this->greeting = $greeting;
}
public function getName()
{
return $this->name;
}
public function greet(Named $greetable)
{
return trim(sprintf(
'%s %s',
$this->greeting->getGreeting(),
$greetable->getName()
));
}
}
Our Person has a required name and we demand it to have a Greeting as well. All it can do besides returning it's name is greet another Named thing, likely another person. And that's it.
To put that all together now:
$greetings->addGreeting($greetingsFactory->createGreeting('Hi'));
$greetings->addGreeting($greetingsFactory->createGreeting('Howdy'));
$greetings->addGreeting($greetingsFactory->createGreeting('Hello'));
$john = new Person('John Doe', $greetings->getRandomGreeting());
$jane = new Person('Jane Doe', $greetings->getRandomGreeting());
echo $john->greet($jane),
PHP_EOL,
$jane->greet($john);
Live Demo on Codepad
Granted that's quite a lot of code for a very simple thing to do. Some will call it overengineered. But you asked for correct OOP and while I am sure there is still room for improvement, it's quite proper and SOLID in my book. And it's easy to maintain now, because the responsibilities are closer to where they should be.
Hmm, two things:
shuffling that array and accessing it from the outside, and having the outside call rely on the array being shuffled, doesn't feel right. It would be nicer to have a method that returns the result of an array shuffling, and maybe also the name straight away.
It would be good style to declare all object properties beforehand so it can be documented later. So if you use $this->name, you should declare it.
Both points implemented could look like this:
class greeting
{
protected $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
protected $name = null;
public function __construct($name)
{
$this->name = $name;
}
public function greet()
{
shuffle($this->greet);
return $this->greet[1]." ".$this->name;
}
}
from a beginners point of view it would be yes, but as this is a single object it cannot be orientated like you could with several objects.
True OOP is when you separate the individual entities of your application into objects / dependencies.
for example, a simple website would include the following:
Database
Error Handling
Sessions
Security
these are called entities and should not interact directly with each other, that's why there separate.
so if we wanted to interact Sessions and Security to make shore that the session is safe, we would add a method to the session object to return a PHP standard result such as array or string, this way many objects can interact with each other without relying on the actual object too much.
Looking at your attempt at a greeting class I would look at something like so:
class User
{
protected $data;
public function __construct(array $user_data)
{
$this->data = $user_data;
}
public function getUsername()
{
return $this->data['username'];
}
}
class Greeting
{
private $message = "welcome to mysite %s";
public function __construct(string $to_greet)
{
$this->message = sprintf($this->message,$to_greet);
}
public function getGreeting()
{
return $this->message;
}
}
the following would be used like so:
$User = new User(array(
'id' => 22,
'username' => 'Robert Pitt'
));
$Greeting = new Greeting($User->getUsername());
echo $Greeting->getGreeting();
now i have mentioned that objects do interact directly with each other but if they do that they should be encapsulated so that all the database objects such as Database,Result,DB_Error would only interact with each other.
this allows for code to be transportable to other projects without having to much of an issue, also known as libraries.
if the objects are closley related ina way that there all bundled together you could do something like this:
$User = new User(/*..From DB ..*/);
$Greeting = new Greeting($User);
echo $Greeting->getGreeting();
It would probably be better to have a greet method. The idea is that the user doesn't need to know that $this->greet is an array.
So:
class Greeting {
protected $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
protected $name='You';
function __construct($name) {
$this->name = $name;
}
function greet(){
shuffle($this->greet);
echo "{$this->greet[0]} {$this->name}!";
}
}
$hi = new Greeting('INSERTNAMEHERE');/*NAME OF PERSON GOES HERE*/
$hi->greet();
I have to disagree with [Edit: Some of] the other answers you've gotten. Making greet private and adding a getter does little to increase encapsulation.
Regardless of that, however, I think it's pretty poor OO design. An object should represent some thing (dare I say, some actual obect?) IMO, the "objects" here would really be the people (or whatever), one of whom is greeting the other. The greeting itself should be a message passed from one of those objects to the other. We might write a "greeting" class to hold the text of the greeting, but even if we do the greeting object itself should be independent of the source or target of the greeting.
It's a bit off the mark, actually. First of all, public variables are generally bad. You shouldn't be accessing class's variables directly from the code. You should try to encapsulate functionality provided by the class into the class itself.
First, let me show you how a good kind of OOP code could look like based on your example:
<?php
class greeting
{
private static $greets = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
private $name;
function __construct ($name)
{
$this->name = $name;
}
function doGreeting ()
{
$i = array_rand(self::$greets);
return self::$greets[$i] . ' ' . $this->name;
}
}
$hi = new greeting('INSERTNAMEHERE');/*NAME OF PERSON GOES HERE*/
echo $hi->doGreeting();
Now, let's talk about the differences here.
First, the greets are stored in a static variable. Since these texts probably do not vary instance by instance, it's simply more efficient to store them in a static variable that is shared by the entire class, so every instance do not have their own copy of the array. You will also notice that it's private. This is encapsulation. The code outside does not need to know about the inner workings of the class, like the variable names. Outside code does not need to know about the array, since it should only be used within the class itself.
Another minor detail, is that the name is also declared there as private, since all class variables should be private in general for encapsulation. If they need to be accessed, that should be done via setter and getter functions, which can provide additional validation for values, if needed.
The code flow is also a bit different. Instead of using the class variables directly from the outside code, we get the class itself to produce the greeting and return it as a string. This way, the outside code does not need to know how the greeting texts are produced or where the name is stored. It jsut needs to know the API, i.e. the functions, their parameters and return values. How they actually work should be left for the class itself.
Additionally, since this is obviously functionality that is intended for the greeting class, it makes the code more reusable as the functionality is coded into the class. Part of the point of OOP is to create good reusable code that can be used where it is needed. When the class functionality is in the class itself, the same code does not needed to be coded elsewhere.
Remember encapsulation and reusability. These are two important points of OOP.
One of the basic ideas behind OOP is that you have objects that have responsibility over certain data structures in your code. what you have written above is really just a data structure, not really a full on object, it holds the data for the greeting, but doesn't really have responsibility over handling it and providing it for other objects.
A "better" object would look something like this:
class greeting {
protected $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
protected $name;
function __construct($name) {
$this->name = $name;
}
public function greet() {
return $this->greet[rand(0,5)] . ' ' . $this->name;
}
}
$hi = new greeting('INSERTNAMEHERE');/*NAME OF PERSON GOES HERE*/
echo $hi->greet();
Now your greet object is in total control of the greeting and your application code doesn't have to care about how that object is set up, it just has to care about the few functions it can use to get the greeting. If you wanted to eventually internationalize or change the greeting in some way, all you'd need to do is change that one object to do it.
Also, just to note, using objects does not make your code OOP. It needs to be object oriented, which means using objects to define discrete tasks that your application will need to perform and not making every other piece of the application have total access to all of it's data to do with what it will. Then, you're just building data structures.
its is not completely correct OOP because the $greet variable is not encapsulated.
to make it 'more correct' (whatever that means), you would have to make the $greet param private and create some get and set methods for it (same goes for the $name variable -- which also should be declared before it is used).
in php a get method is like so:
if i want to get the var:
$hi = new greeting('INSERTNAMEHERE');/*NAME OF PERSON GOES HERE*/
echo $hi->__get('greet') .' '. $hi->__get('name');
the get is created inside the greeting class:
function __get($var){
return $this->$var;
}
and set is the same:
function __set($var, $val){
$this->$var = $val;
}
I would probably use getters/setters for $greet, instead of making it public. I don't see why it wouldn't be considered OOP though.
http://en.wikipedia.org/wiki/Object-oriented_programming