Jump to content

Two Questions: 1) Calling Parent Function 2) Static Function


Recommended Posts

Question 1) Is the only and proper way to call a parent function "parent::function()"?  Are there other/better ways from within a child function?

 

Question 2) What are the deciding factors for when to make a function or attribute static?  How do you make that decision?  Assuming 5.3...

 

Thanks.

Question 1) Is the only and proper way to call a parent function "parent::function()"?  Are there other/better ways from within a child function?

No. See below.

<?php
class foo {
public function __construct() {
}

protected function dostuff() {
 print "Hello World";
}
}

class bar extends foo {
public function __construct() {
 parent::__construct();
 $this->dostuff();
}
}

$x = new bar();
?>

 

Question 2) What are the deciding factors for when to make a function or attribute static?  How do you make that decision?

When you want it to belong to the whole class and not a specific instance of a class (object). i.e

<?php
class foo {
protected static $counter = 0;
public $num;

public function __construct() {
self::$counter++;
$this->num = self::$counter;
}
}
// same class - 2 individual objects
$x = new foo();
print $x->num."<br />"; // prints 1
$y = new foo();
print $y->num."<br />"; // prints 2
?>

 

This essentially means that the static property or method means something to the class but not to the individual object. i.e

<?php
class foo {
public static function convertLbToKg($pounds) {
 return $pounds * 0.45359;
}
}


class bar {
public $kg;
public function __construct($pounds) {
$this->kg = foo::convertLbToKg($pounds);
}
}


// I can call the static method from outside of the class
print foo::convertLbToKg(120)."kg<br />";
// Or it can be called from within another class when creating an object
$x = new bar(150);
print $x->kg."kg<br />";
?>

 

I would recommend you invest in the following:

http://friendsofed.com/book.html?isbn=9781430210115

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.