I am trying to pass a class as a parameter but I do not know if it is possible.
class User {
var $name;
}
class UserRepository {
private $type;
public function __construct(Class) {
$this->type = Class;
}
public function getInstance() {
return new $this->type;
}
}
$obj = new UserRepository(User);
I am accepting suggestions on other ways to do it as well.
Just instantiate the class and call that
$user = new User();
$obj = new UserRepository($user);
Another option (since User contains only variables) is to make the variable static and use that
class User {
public static $name;
}
$obj = new UserRepository(User::$name);
I think you are just looking for a string:
class User {
var $name;
}
class UserRepository {
private $type;
public function __construct($Class) {
^^^^^^ this will be a string
$this->type = $Class;
}
public function getInstance() {
return new $this->type;
}
}
$obj = new UserRepository('User');
^^^^^^ send a string here
var_dump($obj->getInstance());
output:
object(User)#2 (1) { ["name"]=> NULL }
An example.
Related
I have custom class with DI ImapClient $imapClient:
class MailBoxCleaner
{
public function __construct(ImapClient $imapClient)
{
}
}
And there is an facade class:
class ImapConnection {
public function __construct()
{
return new ImapClient();
}
}
I tried to use this like:
$MailBoxCleaner = new MailBoxCleaner(new ImapConnection());
But it does not work.
A constructor never return any data.
You have to create a getter method that return the instance of your ImapClient class, so you inject it in the other class.
Based on your code :
class ImapConnection {
private $imapClient = null;
public function __construct()
{
$this->imapClient = new ImapClient();
}
public function getImapClient(){
return $this->imapClient;
}
}
You can inject :
$idObj = new ImapConnection(); // Instanciation
$MailBoxCleaner = new MailBoxCleaner($idObj->get());
You also can use a "pattern" :
class ImapConnection {
private $instance = null;
private $imapClient = null;
private function __construct()
{
$this->imapClient = new ImapClient();
}
public static function getImapClient(){
if(is_null($this->instance){
$this->instance = new ImapConnection();
}
return $this->instance->get();
}
private function get(){
return $this->imapClient;
}
}
Then, you can use in your code :
$MailBoxCleaner = new MailBoxCleaner(ImapConnection::getImapClient());
I'm wondering if its possible to switch the visibility in PHP. Let me demonstrate:
class One {
function __construct($id){
if(is_numeric($id)){
//Test function becomes public instead of private.
}
}
private function test(){
//This is a private function but if $id is numeric this is a public function
}
}
Is such thing even possible?
I would use an abstract class with two implementing classes: One for numeric and one for non-numeric:
abstract class One {
static function generate($id) {
return is_numeric($id) ? new OneNumeric($id) : new OneNonNumeric($id);
}
private function __construct($id) {
$this->id = $id;
}
}
class OneNumeric extends One {
private function test() {
}
}
class OneNonNumeric extends One {
public function test() {
}
}
$numeric = One::generate(5);
$non_numeric = One::generate('not a number');
$non_numeric->test(); //works
$numeric->test(); //fatal error
It can be faked up to a point with magic methods:
<?php
class One {
private $test_is_public = false;
function __construct($id){
if(is_numeric($id)){
$this->test_is_public = true;
}
}
private function test(){
echo "test() was called\n";
}
public function __call($name, $arguments){
if( $name=='test' && $this->test_is_public ){
return $this->test();
}else{
throw new LogicException("Method $name() does not exist or is not public\n");
}
}
}
echo "Test should be public:\n";
$numeric = new One('123e20');
$numeric->test();
echo "Test should be private:\n";
$non_numeric = new One('foo');
$non_numeric->test();
I haven't thought about the side effects. Probably, it's only useful as mere proof of concept.
in this below class i want to use class like with static methods and for use class methods without create new object from parent.
for example:
<?php
class Permission
{
protected $permission = false;
protected $id = 0;
public static function __construct()
{
return new static;
}
public function user( $id )
{
$this->id = $id;
}
public function check()
{
$this->permission = true;
}
public function item( $item )
{
return $item;
}
}
$bar = Permission::user(100)->item("HELLO");
print_r($bar);
this code not working and have problem. how to resolve this class problem?
That will not work because user method is not static, try changing this two methods, and this is good way of generating objects
public function __construct($id)
{
$this->id = $id;
}
public static function user( $id )
{
return new static($id);
}
I'd suggest you a singleton pattern, like this
class Permission
{
static protected $permission = false;
static protected $id = 0;
private static $_instance = null;
private function __construct () { }
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public static function user( $userId )
{
self::$id = $userId;
return self::$_instance;
}
public static function check()
{
self::$permission = true;
return self::$_instance;
}
public static function item( $item )
{
return $item;
}
}
$bar = Permission::getInstance()->user(100)->item("HELLO");
print_r($bar);
You can chain methods in 'dynamic' classes by returning $this at the end of method (remember, you have a static).
class A {
public function someMethod()
{
// some code
return $this
}
public function otherMethod()
{
// some code
return $this
}
$a = new A();
$a->someMethod()->otherMethod();
}
I have an extended class with an overriden method doSomething().
For some reason the inherited class' method never runs only the base one.
class cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClass();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something';
}
public function call_me() {
$this->doSomething();
}
}
class cDemoClassEx extends cDemoClass {
protected function doSomething() {
echo 'do something differently';
}
}
$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();
result:
do something
do something
The second one should be "do something differently" at least that's what I'm expecting.
Can anyone tell me what I'm doing wrong? Thanks
In this case, you need using late static binding (5.3+). Change in parent method getInstance line :
$instance = new cDemoClass();
to
$instance = new static();
You will get:
do something
do something differently
Read more about this feature here: http://www.php.net/manual/en/language.oop5.late-static-bindings.php
Because cDemoClassEx::getInstance(); is still returning new cDemoClass();. You have to also overwrite the getInstance() method:
class cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClass();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something';
}
public function call_me() {
$this->doSomething();
}
}
class cDemoClassEx extends cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClassEx();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something differently';
}
}
$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();
You have to override with the cDemoClassEx::getInstance() and change this line
$instance = new cDemoClass();
into
$instance = new cDemoClassEx();
You will also need to declare the cDemoClass::__construct() as protected or simply override it in cDemoClassEx.
Bellow is a PHP script.
I tried to implement the Observer pattern (without MVC structure)... only basic.
The error which is encountered has been specified in a comment.
First I tried to add User objects to the UsersLibrary repository. There was a error such as User::update() does not exists or something.
Why is that error encountered? What fix should be applied and how?
interface IObserver {
public function update(IObservable $sender);
}
interface IObservable {
public function addObserver(IObserver $obj);
public function notify();
}
class UsersLibrary implements IObservable {
private $container;
private $contor;
//private $z;
public function __construct() {//IObserver $a) {
$this->container = array();
$this->contor = 0;
echo "<div>[constructing UsersLibrary...]</div>";
$this->addObserver(new Logger());
//$this->z = $a;
}
public function add($obj) {
echo "<div>[adding a new user...]</div>";
$this->container[$this->contor] = $obj;
$this->contor++;
$this->notify();
}
public function get($index) {
return $this->container[$index];
}
public function addObserver(IObserver $obj) {
$this->container[] = $obj;
}
public function notify() {
echo "<div>[notification in progress...]</div>";
foreach($this->container as $temp) {
//echo $temp;
#################################################################
$temp->update(); //--------ERROR
//Fatal Error: Call to a member function update() on a non-object.
#################################################################
}
//$this->container[0]->update();
//$this->z->update($this);
}
}
class User {
private $id;
private $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
}
class Logger implements IObserver {
public function __construct() {
echo "<div>[constructing Logger...]</div>";
}
public function update(IObservable $sender) {
echo "<div>A new user has been added.</div>";
}
}
$a = new UsersLibrary(); //new Logger());
//$a->add(new User(1, "DemoUser1"));
//$a->add(new User(2, "DemoUser2"));
$a->add("Demo");
echo $a->get(0);
//echo $a->get(0)->getName();
Your User class is not implementing interface IObserver and therefore is not forced to have the method update().
You have to instantiate a new User() in order to add it to the UsersLibrary:
$library = new UsersLibrary();
$user = new User(1, "Demo");
$library->add($user);
Also, you are mixing Users and Loggers into your UsersLibrary container. Maybe think about separating the containers for them?
You are passing a string instead of an object in your $a->add() call. You should either pass in an object, or alter the code in UserLibrary::add() to wrap it's argument in an appropriate object (or do an object lookup of it sees a string, for instance find a user with that name).
$user = new User(1, "Demo");
$a = new UsersLibrary();
$a->add($user);