Pass arguments to parent class constructor in PHP? - php

I have 2 classes where parent is inherited by child.
class parentClass
{
private $table_name='';
public function __construct($argument)
{
$this->table_name=$argument;
echo $this->table_name;
}
}
class child extends parentClass
{
private $table="student";
public function __construct()
{
parent::__construct($this->table);
}
}
There is some thing like this below that has to be used but I am unable to understand how and why.
$args = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $args);
Help me as
What should be the correct code to achieve the correct logic
and please support it with a reference to gain a better understanding.

Not a direct answer, but if I read the code correctly, you don't really want to pass a variable / value to the constructor. Instead you want to pass a fixed class property like a table name.
In that case you could use a constant in the child class and set that in the parent's constructor. The child class would not need a separate constructor if that is all you want to do.
So something like:
class parentClass
{
private $table_name;
function __construct() {
$this->table_name = static::TABLE;
echo $this->table_name;
}
}
class childClass extends parentClass
{
const TABLE = "student";
}
$obj = new childClass();

Related

Having child class call parent class

I sometimes find myself performing a similar task on various different related things. For instance, I might have "books", "movies", and "songs", and I might have the task "addNote" which gets the note text from the client, adds it to a database, associates it with the appropriate parent record, and returns some data to the client. I've implemented it as shown below, and while it works, it just seems wrong. Is there a better way to do this, and if so how? Thanks
class parentClass
{
protected function someTask($table)
{
//do the task which is common to child1/2/3Class using $table
}
}
class child1Class extends parentClass
{
public function someTask($dummy=NULL){parent::someTask('class1_table');}
}
class child2Class extends parentClass
{
public function someTask($dummy=NULL){parent::someTask('class2_table');}
}
class child3Class extends parentClass
{
public function someTask($dummy=NULL){parent::someTask('class3_table');}
}
$ajax=new child1Class(); //specific childClass based on MVC
$ajax->someTask();
The way you have it is correct. The only other option you have is making the parent method "public"
class parentClass
{
public function someTask($table)
{
echo "hello " . $table;
}
}
class child1Class extends parentClass
{
// no needed method here
}
class child2Class extends parentClass
{
// no needed method here
}
$obj1 = new child1Class();
$obj1->someTask('class1_table');
$obj2 = new child1Class();
$obj2->someTask('class2_table');
$obj3 = new child2Class();
$obj3->someTask('class3_table');
result with obj1: "hello class1_table"
result with obj2: "hello class2_table"
result with obj3: "hello class3_table"
Public makes the method directly accessible through the object.
Protected makes the method accessible through the child class
Private makes the method only accessible through its own class.

Can I call a private child constructor from a base factory method?

I'd like to implement the following using a private constructor.
The problem is that get_class() returns ParentBase; eventhough; get_called_class() returns ChildClass.
How can I have __construct() be called from the calling class context instead of the base class context?
There will be many child classes, so I only want one shared factory method, and I also want to make sure a child cannot be extended (so that it cannot be created with the new keyword).
Seems like there should be a way of making ChildClass::createObject() work with a private ChildClass constructor and a public ParentBase factory method.
<?php
class ParentBase
{
public static function createObject()
{
echo get_class() . "<br/>"; // prints ParentBase
echo get_called_class() . "<br/>"; // prints ChildClass
return new static();
}
}
class ChildClass extends ParentBase
{
private $greeting = "bye";
private function __construct()
{
$this->greeting = "hi";
}
public function greet()
{
echo $this->greeting;
}
}
$child = ChildClass::createObject();
$child->greet();
The output from the above is:
ParentBase
ChildClass
Fatal error: Call to private ChildClass::__construct() from context 'ParentBase'
Protected contstructor works:
http://codepad.viper-7.com/sCgJwA
Private constructor doesn't:
http://codepad.viper-7.com/YBs7Iz
That is an expected behavior createObject(); is a function of ParentBase, So it will return ParentBase from get_class() but, it was called from ChildClass So, it will return ChildClass from get_called_class().
And about the constructor, since the constructor is assigned as private, you restrict the object creation from within the class only. By making it protected, now Parent Class can create the object of ChildClass
Probable solution would be to override, the createObject() class in the ChildClass itself.
class ChildClass extends ParentBase
{
public static function createObject()
{
echo get_class() . "<br/>";
echo get_called_class() . "<br/>";
return new static();
}
}
Or, you could make the constructor protected, then you will make the constructor accessible to parent classes and restrict any sub classes of child classes making it final, thus making it accessible from parent class only.
The child constructor must be protected or public to my knowledge. I ran into a similar issue for a different problem, I was attempting to access a private property.
But for some reason your question "Can I call a private child constructor from a base factory method?" does not reflect your code so I suggest you edit that as I am troubling myself over how to answer this.
If this is PHP 5.4......
After playing around with some other things and reading up on PHP OOP. It looks like Traits can do this.
I like the use Trait notataion, which in this case makes it obvious that you should use the Factory to instantiate the class.
Using a Trait is advantageous in that it the Factory Trait can be shared across multiple Class hierarchies that do not have common lineages:
<?php
// NOTE: traits are only avaialable in ** PHP 5.4 **
trait Factory
{
public static function createObject()
{
echo get_class() . "<br/>"; // prints ChildClass
echo get_called_class() . "<br/>"; // prints ChildClass
return new static();
}
}
class ChildClass
{
use Factory;
private $greeting = "bye";
private function __construct()
{
$this->greeting = "hi";
}
public function greet()
{
echo $this->greeting;
}
}
$child = ChildClass::createObject();
$child->greet();
Working Code Example

accessing a child class prop from parent

I mean something like that:
class parentClass {
public function method() {
echo $this->prop;
}
}
class childClass extends parentClass {
public $prop = 5;
}
How can I get a child prop from the parent prop?
Thanks...
Either I don't fully understand what you want or the solution is as trivial as the following code.
class parentClass {
public function method() {
echo $this->prop;
}
}
class childClass extends parentClass {
public $prop = 5;
}
$object = new childClass();
$object->method();
I mean the child class is extending the base class which means it will also inherit all the methods of its parent's class. That makes the whole process of using the parent's class method as simple as calling it from the instance of the child class.
All protected and public members of child classes are visible from within their parent class in PHP, so the example code you provided should work just fine. Quote from the php doc:
Members declared protected can be accessed only within the class
itself and by inherited and parent classes.
But the actual question is: do you really need it?
The proper OO way would be to define a self-contained parent class that expresses something. It should not need to access properties of child classes - this is a so-called code smell. If you really think that you have a case where a similar construct is necessary, you are probably looking for abstract methods, which guarantee that every child class has this property:
abstract class Animal {
public function makeNoise() {
echo $this->getNoiseString();
}
protected abstract function getNoiseString();
}
class Cat extends Animal {
protected function getNoiseString() {
return 'meow';
}
}
//parent
class parentClass {
protected $prop = null;
public function method() {
echo $this->prop;
}
}
//child
class childClass extends parentClass {
protected $prop = 5;
}
Make sure the variable is defined in the parentclass as well. So it will be accessible by the parent.

PHP - how to tell the object whos its creator?

HI!
basicly what I ask u to tell me is how to put a "parent" reference into the object
I need it to make example of "extracting method with method object" - one of mostly used refactoring in Java or C#
in Java refering to "parent object" looks like this:
class someClass {
MyObject myObj = new MyObject(this);
}
and thats it :)
but I dont know, how to do the same in PHP
maybe if its imposible you would tell me how you extract your methods out of your classes to new class, that has to do what that method did.
so in other words...
1 - I have class with big and hard to read / refactor method.
2 - I extract that method to new class, giving it fields in place of parameters and method like "execute" - to proced all that this class has to do for me.
3 - I put object of my class to my old function class and I call its method "execute" - so the all logic that was in my_big_method is done.
The best method is inheritance, where you call the parent keyword to access the parent class like so:
class Child extends Father
{
public function __construct()
{
parent::__construct();
}
}
class Father
{
public function __construct()
{
echo "Father says hello";
}
}
new Child();
using the parent keyowrd you can call the constructor like so parent::__construct()
Example: http://codepad.org/kW6dfVMs
if your looking at Injection then you could do something like this.
class Master
{
private $Slave;
public function __construct(Slave $Slave)
{
$this->Slave = $Slave;
}
}
$Master = new Master(new Slave);
if your unsure of the object that should be passed in but you know that it should have a certain interface / set of methods you can get a little more complex and do something like so:
class Master
{
private $Slave;
public function __construct(ISlave $Slave)
{
$this->Slave = $Slave;
}
}
interface ISlave
{
//Declaration of methods
}
class SomeSlaveObject implements ISlave{}
$Master = new Master(new SomeSlaveObject);
Have you tried using the $this keyword?
Easiest way is to pass a reference to the parent object in the constructor, though I may be misunderstanding your goal.
class myClass {
private $parent = false;
function __construct ($parent=false) {
$this->parent = $parent;
}
}
If you are extending a base class, you can use the parent operator:
class otherClass {
function someMethod() {
return 1;
}
}
class myClass extends otherClass {
function aMethod() {
// parent keyword here would refer to "otherClass"
return $this->someMethod();
}
}
Check out the doc on parent: http://php.net/manual/en/keyword.parent.php
PHP version of your example:
class someClass {
public function createObject() {
$myObj = new MyObject($this);
}
}
not much different than java, just less types and more $ signs.
"parent" is a keyword in php, like the java "super" so your question is a little confusing.
I tried with "$this", but "php guy" in my company told me that I cant use $this that is not refering to field or function of current class (that it cant refer to whole class)
my code looks like this:
class to refactor:
class AccountBeforeRefactoring {
// (...)
public function makeTransfer($amount, $destinationAccount){
$transferFee = 1;
if ($amount > 1000){
$transferFee = 1 + $amount * 0.0001;
}
$this->connectToElixir();
// (...)
// (...)
// (...)
$this->debit($amount + $transferFee);
}
}
and it becomes:
class extracted - that was my method:
class TransferMaker {
private $account;
private $amount;
private $destinationAccount;
private $transferFee;
public function __construct($source, $amount, $destinationAccount){
$this->account = $source;
$this->amount = $amount;
$this->destinationAccount = $destinationAccount;
$this->transferFee = 1;
}
public function make(){
if ($this->amount > 1000){
$this->transferFee = 1 + $this->amount * 0.0001;
}
$this->account->connectToElixir();
// (...)
// (...)
// (...)
$this->account->debit($this->amount + $this->transferFee);
}
}
is constructor there made in right way?
and now I need, to make object of MakeTransfer inside my Account class - I tried it this way - is it ok?
class Account {
// (...)
public function makeTransfer($amount, $destinationAccount){
new TransferMaker($this, $amount,
$destinationAccount).make();
}
}
and again - can I just this "$this" just like this? ;)
will my code work? it does compile in Eclipse, but that can mean none.

Is there a way to assign a member variable to an object of a class without a constructor?

I want to do something like the following:
class SomeOtherClass {}
class Test
{
public $member = new SomeOtherClass();
}
The only problem is that I do not want to use a constructor, because the 'Test' class should extend another class and should not override the constructor.
Is this actually possible in PHP?
You can extend parent constructor in Test like this:
class Test extends SomeClass
{
public $member;
function __construct() {
$this->member = new SomeOtherClass();
parent::__construct();
}
}

Categories