Parent:: or $this-> - php

I am starting a new project and i am not sure whats the best/right why of getting the parents methods?
should it be done this why
class ControllerForum extends ControllerAbstract
{
public function __construct()
{
parent::__construct();
}
public function actionViewThread($threadName, (int) $threadId)
{
$threadModel = $this->getModel('ModelThread');
}
}
or this why
class ControllerForum extends ControllerAbstract
{
public function __construct()
{
parent::__construct();
}
public function actionViewThread($threadName, (int) $threadId)
{
$threadModel = parent::getModel('ModelThread');
}
}
Thank you.

They do two different things:
When you call $this->method() you are calling the method() defined in your own child class (ControllerForum in this case).
When you call parent::method() you are calling the one defined in the parent class (ControllerAbstract).
So if we, let's say, define getModel in both ControllerAbstract and ControllerForum (override) then calling one or another will execute different code. I would use the inherited method (the first form) unless you need specific behaviour.
EDIT: #Chris It's inheritance, it means that the child class (that extends the parent class) will have the methods and properties of the parent class. When you use $this->method() you don't call the parent method, you call the method of the current class inherited from the parent class. See PHP 5 inheritance

always code depend on the need
if you are able to create object of class then normally we are use first way
$threadModel = $this->getModel('ModelThread');
the second approach is use when we want to call function without object
$threadModel = parent::getModel('ModelThread');
so it's based on need
Thanks

Related

How to prevent inheritance of static methods? [duplicate]

So let's say I have classes called parent and child, which will be then used from PHP file called caller.php
class Child extends Parent {
}
class Parent {
public function parentMethod(){
}
}
caller.php
PREVENTED:
$child = new Child();
$child->parentMethod();
ALLOWED:
$parent = new Parent();
$parent->parentMethod();
I want to prevent calling parentMethod like this. But if I created Parent object I want to be able to call the parentMethod. Is there some way that I can use to hide this method from being public in Child class, but still allowing parent object to call this method publicly?
Only solution I have come up with so far is making those methods protected and then creating an other class that would extend parent and then have public method for each function that it needs, but that doesn't sound very smart.
Actually, you should ask yourself: why do you need such restriction? You've defined your method as public - thus, you told PHP that it should be visible everywhere. So to prevent child calls you should use private visibility definition.
There is a way to check if call is made from parent class, like:
class ChildClass extends ParentClass {}
class ParentClass
{
public function parentMethod()
{
if(get_class($this) != __CLASS__)
{
throw new LogicException("Somehow due to business logic you're not allowed to call this from childs");
}
}
}
But I would not recommend to do that. Reasons are:
Readability. Your method is just ordinary public method. Looking to it it's impossible to say either you should use it with child calls or not. Thus, to maintain such code you'll need to check that restriction in code. Now imagine that you have ~50 methods like that. And dozen of classes like that.
Possibly, breaking Law of Demeter. Why should parent class be aware of it's childs when using such limitation?
Finally, it's just unexpected behavior. Looking to definition, anybody will see that you're extending one class by another. Thus, by definition all inherit methods with proper visibility must be inherited. And your logic changes that.
You may think about composition, not inheritance. That may be right way to implement your logic (however, I can't tell that for sure since I don't know whole background)
You can rearrange your code by adding a base parent class for both of your mentioned classes. Like so:
class Base {
public function inheritableMethod1() {}
public function inheritableMethod2() {}
}
class Child extends Base {
}
class Parent extends Base {
public function additionalMethod() {}
}
Move all inheritable methods from the Parent class to the Base, and leave there only those which must not be called on Child (the parentMethod in your example).
The base class optionally might be abstract to prevent instantiating it directly.
Check if Abstract Class suits your needs:
PHP: Class Abstraction
class Child extends Parent {
public function parentMethod(
# Code
}
}
Abstract class Parent {
abstract public function parentMethod();
}

Calling a static parent method while instantiating child class

I'm changing my class structure around to store common database methods in one class. Then extending it from a child class. This should cut down on code but also allows me to overwrite the parent methods when I need to.
I've done the following, for this example I've simplified to the basics compared to the original code which contains more classes.
class parent_object{
private $table_name;
public function all_records(){
$sql = "SELECT * FROM ".$this->table_name;
return $this->execute_sql($sql);
}
}
class child_object extends parent_object{
protected static $table_name="tbl_name";
public function __construct(){
parent::__construct(self::$table_name);
}
}
I want to call the all_records() statically to save myself creating a new object every time.
I'm stuck having to instantiate the child and then call the parent method
$child = new child_object();
$all = $child->all_records();
What I really want to be able to call the parent method statically:
$all = child_object::all_records();
I understand why I can't do it with my code, but would like some way that the child instantiates first then accesses the parent method.
I could write all_records() method in the child_object to instantiate itself and call the parent all_records() but that sort defeats the purpose of extending to cut down on code and the same methods in my child class.
I'm sure its quite simple or some new high level oop function can do it.
Thanks for your help.
The answer is relatively simple, you can turn all your properties into static properties, and then use static:: instead of self::.
http://php.net/manual/en/language.oop5.late-static-bindings.php
Solving your problem this way is considered a bad practice though. Good luck.
You could do something like this:
class child_object extends parent_object
{
protected static $table_name="tbl_name";
public static function factory()
{
return new child_object();
}
public function __construct()
{
parent::__construct(self::$table_name);
}
}
Then when you use it you just do:
$all = child_object::factory()->all_records();

Can you explain how Zend's Action controller operating?

Sorry for constantly re-editing my question but looks like this is the only way to ask it properly.
My original problem is the following pseudo-code (a controller and it's parent) isn't working as i would like to:
class Parent {
var $data = array();
public function __construct( OtherClass $otherClass ) {
$this->data = $otherClass->getData(); //contains some => thing
$this->init($otherClass->getClassName());
}
public function init( $className ) {
new $className; //new Child
}
public function __get( $name ) {
return array_key_exists($name, $this->data) ? $this->data[$name] : null;
}
}
class Child extends Parent {
public function __construct() {
echo $this->some; //won't return 'thing';
}
}
fireeyedboy helped me a lot (thank you) and pointed out Zend_Controller_Action is doing what i want but i can't understand how they do it?
Original question
I know there was some similar questions here but i cannot dump them. Also i know i can reverse the whole process so i can initialize Child first then call parent::__construct but this seems unwanted for me. How can i access Parent variables easily in my case?
Update:
Let me clarify a little bit. Child is an arbitrary controller. Parent is the mother of all controllers. Many frameworks are doing the same but controllers can utilize their parent controllers variables, methods or objects without calling parent::__construct (and therefore filling child class constructors with unnecessary arguments). I don't like to rewrite any of these frameworks but i'd like to understand how they're operating.
Your child class doesn't call parent constructor. Here's a fix:
class Child extends Parent {
public function __construct() {
parent::__construct();
echo $this->some;
}
}
Update: Parent classes' constructors aren't called automatically in PHP. See the documentation:
Note: Parent constructors are not
called implicitly if the child class
defines a constructor. In order to run
a parent constructor, a call to
parent::__construct() within the child
constructor is required.
So what you're asking does not happen. Either you have misinterpreted the class structure or how they operate. Note that PHP also supports legacy constructor naming (at least until 5.3.3): If there is no __construct() method in a class, PHP assumes the constructor is named after the class (ie. class Foo { function Foo() {}) treats the Foo() method as constructor).
Injecting ANYTHING using controller's construct is generally a BAD PRACTICE! Problem lies in your design. What kind of object is OtherClass? Is it DB adapter? Is it ACL? Is it some helper class?
If you need external class in your controller I suggest using action helpers. That's what they are created for ;) Or create an action helper that will fetch this OtherClass from somewhere when needed.
You should NEVER use __construct() to do any of your dirty work. That's what init() is used for. But it has no params. And there is a reason for that - again - you should not inject dependencies like this ;)
Update:
Note your class uses discouraged PHP4 member variable definition syntax. Try replacing your var with protected.
The problem is that your Child class does not call the base constructor.
Incidentally, Parent is not a valid class name in PHP. I have changed the class names for clarity. See below:
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct(/* what goes here? */);
echo $this->some;
}
}
However, note the what goes here? part: your base class requires a reference to an OtherClass instance to be constructed. Therefore, since ChildClass IS-A ParentClass, it also needs to get such an instance somehow. You will need to either add a parameter to ChildClass::__construct and forward the value to parent::__construct, or somehow figure out a default value yourself.

using $this or parent:: to call inherited methods?

Not really a problem, more like curiosity on my part but as an example, say I have a php class:
class baseTestMain
{
protected function testFunction()
{
echo 'baseTestMain says hi';
}
}
and another class that extends from that class above:
class aSubClass extends baseTestMain
{
public function doingSomething()
{
parent::testFunction();
//someextrastuffhere
}
}
Normally, when I want to call a parent method when defining a new method in the subclass I would do the above - parent::methodnamehere() however instead of parent:: you can also use $this->methodname() and the operation would be the same.
class aSubClass extends baseTestMain
{
public function doingSomething()
{
$this->testFunction();
//someextrastuffhere
}
}
So what I'm asking is, should I use parent::testFunction(); or use $this->testFunction(); ? or is there a difference to it that I've missed? If not, whats your preference or the preferred method?
Do note that I am not overriding or extending that function in the subclass, essentially the implementation is carried over from the parent.
In your case, since aSubClass::testFunction() is inherited from baseTestMain::testFunction(), use $this->testFunction(). You should only use parent::testFunction() if you're going to override that method in your subclass, within its implementation.
The difference is that parent:: calls the parent's implementation while $this-> calls the child's implementation if the child has its own implementation instead of inheriting it from the parent.
Calling the method on the parent prevents the class's children from participating in polymorphism properly since their redefinition of the method will never be called.

Is Superclass's constructor run inside child constructor in PHP?

If I have this class:
<?php
class Model
{
var $db;
function Model()
{
$this->db=new Db_Class();
}
}
?>
and a second class that extended the parent class:
<?php
class LessonModel extends Model
{
public function LessonModel()
{
//code here
}
public function getTitle($id)
{
$this->db->setTable('myTable');
return $this->db->get('title',$id);
}
}
?>
Is it safe to assume that the $LessonModel->db field would have been instantiated by the parent Model class's constructor, or do I need to run it manually using something like parent::Model();?
You cannot assume that the parent constructor has been called because you have overridden this in your subclass. You would need to call parent::Model() as you suggest. If you change the class you are inheriting from you would obviously need to change this.
If you are using PHP5 then you can name your constructors __construct(). This has the benefit of letting you easily call a parent constructor by doing parent::__construct() in any derived class without specifying the parent class name. You can then rearrange your classes' inheritance with less hassle and less danger of introducing obscure bugs.
In the given example, you can assume that.
However, if your child class defines a constructor, PHP will not implicitly call it's parent constructor.
In order to do that, call:
parent::__construct();
There's a cheap way to get around having to call the parent constructor.
Create an empty init() method in the base class. Call $this->init() in the base class constructor.
All sub-classes can implement init() if they want to run code when the class is created.

Categories