Page 1 of 1
Interface Method Visibility
Posted: Fri Oct 29, 2004 11:37 am
by andre_c
I have an interface called ISess and I am setting the visibility of the constructor as private:
Code: Select all
<?
interface ISess {
private function __construct ();
static public function instantiate ();
}
?>
when I try to implement it, i get the following error:
Code: Select all
Fatal error: Access type for interface method ISess::__construct() must be omitted or declared public in <path>
Any Ideas why i'm not allowed to set the visibility of the constructor as private?
Posted: Fri Oct 29, 2004 12:32 pm
by timvw
if it's private.... only instances of that class have access too it.
for an implementation of an interface this means that you don't have access to the function that you have to implement....

Posted: Fri Oct 29, 2004 12:35 pm
by andre_c
I see.
Then it should work when I change the visibility to protected, but it still gives me the same error.
Posted: Fri Oct 29, 2004 12:40 pm
by timvw
__construct is the name for the constructor..
i guess php thinks : interface can't be created, thus it's impossible to have a constructor.
Posted: Fri Oct 29, 2004 12:46 pm
by andre_c
I know, the method instantiate will return a instance of the class:
Code: Select all
<?
class DomainsSess implements ISess {
protected function __construct () {
// code
}
static public function instantiate () {
return new DomainsSess;
}
}
// this should create a new instance
$domains_session = DomainsSess::instantiate();
// this should return an error
$domains_session = new DomainsSess;
?>
I want every instance of this object created using the instantiate() method, and not using the new operator from outside the class.
So if the inteface constructor has a protected visibility, it should be accessible and overridable from a sub-class and not from the outside.
Posted: Fri Oct 29, 2004 12:51 pm
by timvw
ah, singleton pattern
Code: Select all
<?php
abstract class Foo {
private static $foo;
private function __construct() {
// constructing stuff
}
public function __clone() {
return $this->getFoo();
}
public function getFoo() {
if ($this->foo == null) {
$this->foo = new Foo();
}
return $this->foo;
}
}
?>
Posted: Fri Oct 29, 2004 12:53 pm
by andre_c
close but not exactly a singleton,
I want to allow for more than one instance if necessary.
(nice implementation of a singleton on your code by the way)
Posted: Fri Oct 29, 2004 4:34 pm
by andre_c
It seems that php doesn't allow the constructor on an interface to be have protected visibility.
A class that implements this type of interface (protected constructor) can instantiate objects from within a static method.
So it would seem possible to have a protected constructor on an interface.
Anybody know why php won't allow it?