You are here: Re: PHP5 Singlton vs. Abstract Classes « All PHP « IT news, forums, messages
Re: PHP5 Singlton vs. Abstract Classes

Posted by Oli Filth on 10/13/75 11:30

Dikkie Dik said the following on 27/10/2005 23:20:
> Daedalus.OS wrote:
>
>> And even with, for example, the Math class (static class), would the
>> right way to go would be to create a normal class with static
>> funtions and a private constructor (since there can be no instance of
>> that class) rather than using an abstract class with static functions ?
>
>
> The PHP help does not say anything about private constructors. I guess
> it is a java thing to make them private to disallow instantiation.

Not just a Java thing.


> If you think about it, it is quite odd. The constructor is never called
> directly, but it is a language construction. You give a "new" keyword,
> some space in memory is reserved, the class name is attached to it as a
> type, and its constructor is called. By whom? By the virtual machine
> itself, basically.

> Making it private is _really_ odd.

Actually, it's a *very* common design pattern in many OO languages.


> It is not very consequent either. "private" in java means "visible only
> within the same instance". Only for constructors it suddenly means
> "visible within the same class".

Not true. "Private" means visible within the same class, e.g.:

class Foo
{
private $v;

function bar($theFoo)
{
echo $theFoo->$v;
}
}

$a = new Foo;
$b = new Foo;
$b->bar($a);

The equivalent works in Java, C++ and C#.


> Declaring it abstract will certainly stop instantiation. However,
> "abstract", communicates that it is meant as a superclass. I would not
> create a constructor at all and not declare it abstract either. As the
> static operator differs from the normal method calling, it is clear
> enough that instantiation is pointless. Any instance does not have
> properties or methods that can be called on it.

One of the ideas of writing good OO code is to explicitly enforce a
well-defined interface on your classes' users, i.e. what they can and
can't do with it. If you don't want them to be able to instantiate a
Foo, enforce it with a private constructor, don't leave it to chance.

Another example would be, if it makes no semantic sense for a Foo to
ever be extended, explicitly say so with the "final" keyword.



--
Oli

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация