0

im using the following type of class...

class datas{ protected $req ; protected $db ; private function __construct() { $this->db = new Database('localhost', 'user', 'pass', 'db'); $this->db->connect(); } public function prnt() { echo "afafa6e5f1ga56d18a1ge"; } } 

when i try and access the class like

$y = new datas(); $y->prnt(); 

Call to protected data::__construct() from invalid context

when i turn it to public, it works. is there any way to make the constructor private and still have the method of call like i have. and i was thinking which one is more secure .

any insight is appreciated guys.

2
  • A class with private or protected cannot be instantiated. See stackoverflow.com/questions/1997721/…. Commented Jul 26, 2013 at 17:21
  • 2
    note there is a discrepancy between the class name and visibility in the class and in the error message (data vs datas, protected vs private). In any case, a non-public ctor obeys the same rules as any other non-public method in terms of where it can be called. Commented Jul 26, 2013 at 17:21

2 Answers 2

2

Your constructor should be public because it's being called outside of the class context.

PHP may hide that for you, with new, but that's still what's happening.

Sign up to request clarification or add additional context in comments.

4 Comments

is there a way to call it inside the class context ?
You could create a static public member function on the class, and have it return new datas();. Instead of using new to create a new instance outside the class, you'd use $x = datas::MyStaticFunction();
yeah, but why? I mean, if the OP can change the class, then s/he can just as well change the ctor back to public.
I'm not here to ask why; I'm just answering their questions. But this would just be a Factory pattern. There could be any number of reasons to do this, and some of them are actually legitimate. In a real world example, maybe datas is an abstract base class and datas::MyStaticFunction() will return a different subclass of datas depending on which database the user configured for the app.
-1
$y = new data(); 

should be

$y = new datas(); 

6 Comments

yea ok...that was just a typo..thanks...
could the issue be in Database class constructor ? if I comment out the DB connection part (since I don't have code for that class), your code seems to be working.
nah changed it....it should have been private function __construct()
why do you want a private constructor ?
given that the ctor holds a Database class my assumption is that this is an attempt at creating a Singleton.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.