473,663 Members | 2,743 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling the parent constructor from a child class automatically.

dlite922
1,584 Recognized Expert Top Contributor
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 17927
realin
254 Contributor
I believe PHP calls its nearest constructor. if you need to call constructor from parent you can explicitly call it using parent::__const ructor();

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::__const ruct();
}

}

$test = new Child();

?>[/PHP]


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

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::__const ruct();
}

}

$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 Contributor
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 Recognized Expert Expert
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 Contributor
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 Recognized Expert Top Contributor
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...hen ce 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("b lah.php"); //etc...

$customerCT = new CustomerCT();

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

$smrty->dispay("custom er.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_ACT ION)
{
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 Recognized Expert Expert
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 Recognized Expert Top Contributor
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::__const ruct() inside each of my child's constructors.

I was trying to avoid that.
Jun 16 '08 #9
Mikeemoo
2 New Member
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

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

Similar topics

2
3869
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 = & $object; if (method_exists($object, "setCallingCode")) $object->setCallingCode($nameOfFunctionOrClassCalling); return $object; } else {
3
3534
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 in one of my classes I need to do some calculations first and THEN call the parent's constructor. Here is an example: class ParentClass { public: Parentclass(int sum);
3
11435
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 does somthing that must be done. This meens that when a child class inherits the class and creates its own vertual int A() the parent class must also be called. the prob is i can not use the base class name and then its functino name after it...
2
5795
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) has to be called too early. Is this possible please? Parent constructor public class CommException : System.ApplicationException {
1
5154
by: Xarky | last post by:
Hi, Having the following scenario: public class Parent { private string Parent_name; public Parent() { this.Parent_name = "";
1
1449
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, Duncan. -------------------------------- From: Duncan Aitken
10
19608
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 Class Parent '*** HOW TO DECLARE IT *** Dim Age As String = "1/1/2000"
4
3253
by: markww | last post by:
Hi, I have a two classes setup like this: class CChild { void Something(); }; class CParent { string m_strData;
2
2258
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 following code: #include <stdio.h>
0
8345
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8771
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8548
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7371
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5657
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4349
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.