0

I created a class with a constructor (__construct()), but I don't want anyone to be able to access it. How can I do that? Thank you very much!

Edit 1:

For more detail: I created a class:

<?php
class test{
    function __construct()
    {
        $a=1;
    }
}
$t = new test;
$t->//here's the problem
?>

In my editor, when press $t->, the code hint shows the ('_construct()') and ('$a') too. I want to ask: Can someone else can acces ('$a') or ('_construct()'). How can I prevent that,

Marcus
  • 12,296
  • 5
  • 48
  • 66
user3098638
  • 45
  • 1
  • 5
  • You cannot have a class without it beeing constructed. If you don't want to run any code on object construction, simply don't use a constructor. – Daniel W. Jan 02 '14 at 08:59
  • 1
    Can I ask why you would want this behavior? What is your reasoning behind this request? – Lix Jan 02 '14 at 09:01

2 Answers2

2

Just make the constructor private

class Test {
    private function __construct() {}
}
Petah
  • 45,477
  • 28
  • 157
  • 213
  • Then no one can use the class, it's just a block of bytes. –  Jan 02 '14 at 09:02
  • But you *did* answer the question. –  Jan 02 '14 at 09:02
  • 2
    @jdersen its commonly used in the singleton pattern, static methods of the class can create instances. – Petah Jan 02 '14 at 09:02
  • 1
    @jdersen - Take a look at [this post](http://stackoverflow.com/questions/26079/in-a-php5-class-when-does-a-private-constructor-get-called) for an example usage. – Lix Jan 02 '14 at 09:03
  • 3
    Indeed; this would be used in the [singleton pattern](http://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5). – Matt Gibson Jan 02 '14 at 09:03
  • Ah, okay. Thanks. Learn something new every day :) –  Jan 02 '14 at 09:04
  • the static method which creates the instantiation will still have the constructor itself, because of returning self. Simply var_dump the static method will expose the same information, as dumping the class instantiation. – Royal Bg Jan 02 '14 at 09:10
0

If you don't let any access the constructor function for your class - no one will be able to use that class as they will not be able to instantiate it.

In any case, if they have your class file they will be able to look at the source code and see the constructor.

Lix
  • 47,311
  • 12
  • 103
  • 131