473,395 Members | 1,972 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Calling the parent constructor from a child class automatically.

dlite922
1,584 Expert 1GB
If I have

[PHP]
class Parent
{
function __construct()
{
die("I'm In Parent");
}

}

class Child extends Parent
{
function __construct()
{
echo "going through child constructor...";
}
}

$test = new Child();

[/PHP]

The above code does not print the die statement.

I expected it to do so. Bug or By Design?
Jun 13 '08 #1
11 17902
realin
254 100+
I believe PHP calls its nearest constructor. if you need to call constructor from parent you can explicitly call it using parent::__constructor();

So if the child (extending class) doesn't have any constructor then it calls parent constructor by default. Same goes for the case of grandparent constructor. See for example ::
[PHP]
<?
class top{
function __construct()

{

echo ("I'm In GrandParent");

}
}
class A extends top

{




}


class Child extends A

{

}

$test = new Child();

?>[/PHP]

now for your piece of code we can call the parent constructor using the following snippet of code ::
[PHP]
<?
class A

{

function __construct()

{

die("I'm In Parent");

}

}
class Child extends A

{

function __construct()

{

echo "going through child constructor...";
parent::__construct();
}

}

$test = new Child();

?>[/PHP]


hope this helps :)
cheers !!
Jun 13 '08 #2
dlite922
1,584 Expert 1GB
I believe PHP calls its nearest constructor. if you need to call constructor from parent you can explicitly call it using parent::__constructor();

So if the child (extending class) doesn't have any constructor then it calls parent constructor by default. Same goes for the case of grandparent constructor. See for example ::
[PHP]
<?
class top{
function __construct()

{

echo ("I'm In GrandParent");

}
}
class A extends top

{




}


class Child extends A

{

}

$test = new Child();

?>[/PHP]

now for your piece of code we can call the parent constructor using the following snippet of code ::
[PHP]
<?
class A

{

function __construct()

{

die("I'm In Parent");

}

}
class Child extends A

{

function __construct()

{

echo "going through child constructor...";
parent::__construct();
}

}

$test = new Child();

?>[/PHP]


hope this helps :)
cheers !!
Yeah thanks, I knew you could manually call it, but what's the point of having a constructor then. Defeats the purpose of automation.

I could place my task in a different function and call that instead.

I"m disappointed, this ruined my chance of a good framework I am building.

Thanks,

Dan
Jun 13 '08 #3
realin
254 100+
yup..
its doesn't call it automatically.. jus like it happens in java
may be there is some solution out ..
Jun 13 '08 #4
Atli
5,058 Expert 4TB
I don't get the problem.

Why would you want the parent constructor to be called automatically?
Even as it is not, would it not be just as effective to create a constructor that calls it's parent constructor?
Jun 13 '08 #5
realin
254 100+
I don't get the problem.

Why would you want the parent constructor to be called automatically?
Even as it is not, would it not be just as effective to create a constructor that calls it's parent constructor?
agreed.. cause that way you have a choice .. cause this gives you both options:

To call a parent constructor, if needed
Parent constructor do not gets called by default


But in case of java, i see no way u can ask proggie not to call Parent constructor if it exists in there.. Correct me if i am wrong ..
Jun 13 '08 #6
dlite922
1,584 Expert 1GB
agreed.. cause that way you have a choice .. cause this gives you both options:

To call a parent constructor, if needed
Parent constructor do not gets called by default


But in case of java, i see no way u can ask proggie not to call Parent constructor if it exists in there.. Correct me if i am wrong ..
Okay you need a scenario, take mine.

I"m using my home-cooked MVC architecture and I keep building it.

Most of my pages have a few variables that I need to check for each single time. This is the "pageAction" variable. 99% of pages will have it.

I wanted to automatically get this pageAction from POST and put it in a var in the parent, that way the child controller does not have to do this everytime...hence automation.

If I have to call some constructor, or some function, I could just make it a rule and make sure each controller child class grabs the pageAction (They always have to if the page is not static)

For example here's a .php page that uses a customer controller (CT)
(I'm just typing this as i go and is not actual code)
[PHP]

//my includes
require_once("blah.php"); //etc...

$customerCT = new CustomerCT();

switch($customerCT->getPageAction())
{
case "Add":
$customerCT->add();
break;
case "Update":
$customerCT->update();
break;
}

$smrty->dispay("customer.tpl");


[/PHP]

That's an over-simplified version of my architecture. In the constructor of CustomerCT I get POST variables that are specific to that page. "pageAction" is very common, exists on all pages with a submit button.

How do other frameworks do it (Cake, Zend, Symphony).

In the global include, or index.php file, they just grab it and put it in a global variable?

I guess that's one way.

So I could do

[PHP]

switch(PAGE_ACTION)
{
case "Add" ....

[/PHP]

I guess that would work...yes? is it cleaner?

pbmods is good at ZendF, hopefully he can shed some light on this.

Thanks guys,

Dan
Jun 16 '08 #7
Atli
5,058 Expert 4TB
I would do it inside the Control object. Somewhat like:
Expand|Select|Wrap|Line Numbers
  1. class BaseCT {
  2.   protected $action;
  3.   public function __construct() {
  4.     $this->action = @$_GET['action'];
  5.     // And whatever other global CT constructor logic
  6.   }
  7. }
  8.  
  9. class SomepageCT extends BaseCT {
  10.   public function __construct() {
  11.     parent::__construct();
  12.     // And whatever specialized constructor logic
  13.   }
  14.  
  15.   public function execute() {
  16.     switch($this->$action) {
  17.       case "Add":
  18.           $this->_addSomething();
  19.           break;
  20.       case "Edit":
  21.           $this->_editSomething();
  22.           break;
  23.       default:
  24.           $this->_displaySomething();
  25.           break;
  26.     }
  27.   }
  28.  
  29.   // Plus the private functions used by the execute method.
  30. }
  31.  
Then I could call all pages somewhat like:
Expand|Select|Wrap|Line Numbers
  1. $className = (isset($_GET['page']) ? $_GET['page'] ."CT" : "DefaultCT");
  2. $page = new $className();
  3. $page->execute();
  4.  
Is this not basically what you were trying to do?
Jun 16 '08 #8
dlite922
1,584 Expert 1GB
I would do it inside the Control object. Somewhat like:
Expand|Select|Wrap|Line Numbers
  1. class BaseCT {
  2. protected $action;
  3. public function __construct() {
  4. $this->action = @$_GET['action'];
  5. // And whatever other global CT constructor logic
  6. }
  7. }
  8.  
  9. class SomepageCT extends BaseCT {
  10. public function __construct() {
  11. parent::__construct();
  12. // And whatever specialized constructor logic
  13. }
  14.  
  15. public function execute() {
  16. switch($this->$action) {
  17. case "Add":
  18. $this->_addSomething();
  19. break;
  20. case "Edit":
  21. $this->_editSomething();
  22. break;
  23. default:
  24. $this->_displaySomething();
  25. break;
  26. }
  27. }
  28.  
  29. // Plus the private functions used by the execute method.
  30. }
  31.  
Then I could call all pages somewhat like:
Expand|Select|Wrap|Line Numbers
  1. $className = (isset($_GET['page']) ? $_GET['page'] ."CT" : "DefaultCT");
  2. $page = new $className();
  3. $page->execute();
  4.  
Is this not basically what you were trying to do?
Yeah you've got the right idea. Mine does the same thing as well if i call parent::__construct() inside each of my child's constructors.

I was trying to avoid that.
Jun 16 '08 #9
to force the call of a parent constructor you can use the 'final' keyword on the parents constructor.

of course, this means it can NEVER be overwritten, so use with caution.

[PHP]
class A {
final function __construct ($my,$args){
die("i've been called");
}
}
class B extends A{

}

$myobj = new B("hello", "world");

// i've been called
[/PHP]
Jul 15 '08 #10
actually now that i've said that i don't think it's true.

possibly ignore me.

(he says 1 month after OP asked the question..)
Jul 15 '08 #11
Atli
5,058 Expert 4TB
Actually, what happens is that when the child class does not have a constructor, the parent constructor will be called automatically.

Adding the "final" keyword the the constructor of the parent only prevents the constructor from being overridden. It will be called by default whether it is final or not.

So that really doesn't change anything. If you create a constructor for the child, the parent constructor will not be called unless you call it manually.
Jul 16 '08 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: lkrubner | last post by:
My code was dying on the line below where I use method_exists: if (class_exists($nameOfClassToBeUsed)) { $object = new $nameOfClassToBeUsed(); $this->arrayOfAllTheObjectsSoFarLoaded = &...
3
by: pantalaimon | last post by:
I'm trying to write a GUI for a game I'm making. Till now I've always done this: ChildClass(int x,int y) : ParentClass(x,y) whenever my compiler complains about "no default constructor found". But...
3
by: scott | last post by:
hi all, hope some one can help me. Ill try and explain what im trying to do as best i can. i have a parent class that has a vertual function, lets call it virtual int A(). That vertual function...
2
by: Claire | last post by:
My descendent constructor takes a string and an integer as parameters. I'd like to format the message string before passing it to it's parent class but it looks as though base(message,ErrorCode)...
1
by: Xarky | last post by:
Hi, Having the following scenario: public class Parent { private string Parent_name; public Parent() { this.Parent_name = "";
1
by: Duncan Aitken via .NET 247 | last post by:
All, In an inherited managed c++ class, how do you call the contstructor of the parent class? I tried with the usual Parent::Parent(...), but get compiler error C3257. Any ideas? Thanks, ...
10
by: Goran Djuranovic | last post by:
Hi all, Does anyone know how to declare a variable in a class to be accessible ONLY from a classes instantiated within that class? For example: ************* CODE ***************** Public...
4
by: markww | last post by:
Hi, I have a two classes setup like this: class CChild { void Something(); }; class CParent { string m_strData;
2
by: Korosov | last post by:
Hi! GCC (4.1.2 20070502 (Red Hat 4.1.2-12)) gives an error: test.cpp: In constructor <Dclass<T>::Dclass()>: test.cpp:27: error: <a> was not declared in this scope when compiling the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.