Is there a way to codify the following in PHP:
class myClass extends parentClass{
function myFunction(){
calculate();
}
}
class parentClass{
public function calculate(){
}
}
Or is $this-> always required?
class myClass extends parentClass{
function myFunction(){
$this->calculate();
}
}
You need $this-> in functions, defined as class methods.
Also you can use global functions out of classes, they neednot $this->
function myMethod() { echo "Outside Class Scope"; }
class A {
function myMethod() { echo "Inside Class Scope"; }
function what_to_call() {
myMethod();
}
}
What function should PHP execute when it encounters myMethod() within class A''s what_to_call() method?
Also consider a long chain of inheritance, with each ancestor having its own myMethod(). What method should PHP call? The current objects'? The parents'? The grandparents'?
You need to use this $this-> when you're calling method
$this-> must be used if you're referring to a method (i.e. a function defined inside of a class). calculate() on it's own refers to a function outside of the class (just like any build-in function), which is not what you want.
$this-> my_function
This statement is for call an function into a Class :)
Related
I declare my class in PHP and several functions inside. I need to call one of this functions inside another function but I got the error that this function is undefined. This is what I have:
<?php
class A{
function b($msg){
return $msg;
}
function c(){
$m = b('Mesage');
echo $m;
}
}
This is basic OOP. You use the $this keyword to refer to any properties and methods of the class:
<?php
class A{
function b($msg){
return $msg;
}
function c(){
$m = $this->b('Mesage');
echo $m;
}
}
I would recommend cleaning up this code and setting the visibility of your methods (e.e. private, protected, and public)
<?php
class A{
protected function b($msg){
return $msg;
}
public function c(){
$m = $this->b('Mesage');
echo $m;
}
}
You can use class functions using $this
<?php
class A{
function b($msg){
return $msg;
}
function c(){
$m = $this->b('Mesage');
echo $m;
}
}
You need to use $this to refer to the current object
$this-> inside of an object, or self:: in a static context (either for or from a static method).
To call functions within the current class you need to use $this, this keyword is used for non-static function members.
Also just a quick tip if the functions being called will only be used within the class set a visibility of private
private function myfunc(){}
If you going to call it from outside the class then leave it as it is. If you don't declare the visibility of a member function in PHP, it is public by default. It is good practice to set the visibility for any member function you write.
public function myfunc(){}
Or protected if this class is going to be inherited by another, and you want only the child class to have those functions.
protected function myfunc(){}
My Class is independant from another Class.
Inside my Class, a function is doing the same but refined job as a function in another Class. Can I use parent:: function_in_another_class() and get my function join that parent funciton's job flow?
No.
In PHP you can only extend from none or one class. As you write both classes are independent to each other, there is no information where to find the one or the other class.
But what you're looking for is probably this:
class A
{
function myFunction() {}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function myFunction()
{
$this->a->myFunction();
}
}
If any class method already doing the same thing why would you bother call join it?
You can not do it. If you want the same job flow best way to do is to instantiate the other class and invoke that very same method. Thats why we use OOP.
See the example,
interface Fable()
{
public function f();
}
class OtherClass implements Fable
{
public function f()
{
// job flow
}
}
class MyClass
{
private $fable;
public function __construct(Fable $f)
{
$this->fable = $f;
}
public function method1($args){
return $this->fable->f($args);
}
}
If the current class is a child of another class, yes, you can. parent references to the parent class.
From php.net:
<?php
class A {
function example() {
echo "I am A::example() and provide basic functionality.<br />\n";
}
}
class B extends A {
function example() {
echo "I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?>
The best you can do here is to extend Class B from Class A
Class B extends Class A
But, you can also:
class ClassA {
function do_something($args) {
// Do something
}
}
class ClassB {
function do_something_inclassA($args) {
classA::do_something($args);
}
}
Important: calling classa::do_something(); is a static call, in other words with error reporting E_STRICT you will get a static notice warning because function do_something() is not static function do_something()
Also, calling this function statically (i.e. classa::do_something()) means that class a's function cannot refer to $this within it
When I defined a function in a supertype and called without parent:: it gave me and error teling me it's undefined function. I am wondering if I should use parent:: each time or if I am doing something wrong somewhere else.
I have a class, named core, which has an escape() function for escaping strings
I am trying to call this function from subtypes.
all methods are static.
Right now I don'T think static methods are inherited. I call all the static superclass methods with
parent::mystaticmethod()
now. Because static methods are not inherited.
use parent:: only when you are going to override function in your child class
Best way to explain this is this example:
class Parent {
function test1() {}
function test2() {}
function __construct() {}
}
class Child extends Parent {
function test1() {} // function is overrided
function test3() {
parent::test1(); // will use Parent::test1()
$this->test1(); // will use Child::test1()
$this->test2(); // will use Parent:test2()
}
function __construct() {
parent::__construct() // common use of parent::
... your code.
}
}
Practical example (static methods):
class LoaderBase {
static function Load($file) {
echo "loaded $file!<br>";
}
}
class RequireLoader extends LoaderBase {
static function Load($file) {
parent::Load($file);
require($file);
}
}
class IncludeLoader extends LoaderBase {
static function Load($file) {
parent::Load($file);
include($file);
}
}
LoaderBase::Load('common.php'); // this will only echo text
RequireLoader::Load('common.php'); // this will require()
IncludeLoader::Load('common.php'); // this will include()
Output:
loaded common.php!
loaded common.php!
loaded common.php!
Anyways using parent:: is more useful in non-static methods.
As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.
More information here http://php.net/manual/en/language.oop5.late-static-bindings.php
I noticed that if I declare a function inside a class method that has the same name as a outside function I get a error:
function a(){
...
}
class foo{
public function init(){
function a(){ // <- error
...
}
...
}
}
this however would work:
function a(){
...
}
class foo{
public static function a(){
...
}
}
Can I include a set of functions that act as static methods for this class using require_once or something like that?
require_once('file.php'); after class foo{ doesn't work...
PHP allows to nest function declarations in others, but it doesn't actually have nested functions. They always end up in the global scope. So the a() that you define in your init method clashes with the already defined function a().
The static function a() is associated with the class namespace, even if it behaves like a function, not a method.
Invoking a require_once statement in a class definition is not possible. The PHP syntax does not allow for it. Class definitions are special scopes / language constructs, that only allow function or variable declarations within the immediate parsing level. - So PHP does not allow for that (classes and their methods must be declared at once, not assembled), and there are no really nice or advisable workarounds for what you want.
If your class structure allows, you can split the class into several different classes which are part of an inheritance chain:
class foo1 {
public static function a() {}
}
class foo extends foo1 {
public static function b() {}
}
Alternatively, you can use __callStatic() if you are willing to take the performance hit. (Requires PHP 5.3; though if you only need non-static methods, __call is available from 5.0.) Smarty 3 does this IIRC.
class foo {
private static $parts = array('A', 'B');
public static __callStatic($name, $arguments) {
foreach (self::$parts as $part) {
if (method_exists($part, $name)) {
return call_user_func_array(array($part, $name), $arguments);
}
}
throw new Exception();
}
}
class A {
public static function a() {}
}
class B {
public static function b() {}
}
PHP 5.4 will supposedly include traits, which are a more straightforward way of including external code in a class:
class foo {
use A, B;
}
trait A {
public static function a() {}
}
trait B {
public static function b() {}
}
To answer the question: you should first check whether or not the function a has already been implemented by using function_exists:
class foo{
public function init(){
if(!function_exists('a')):
function a(){ // <- will only be declared when it doesn't already exist
...
}
endif;
...
}
}
However, consider this as a very bad coding practice. It will get a mess pretty soon as you have no idea of what's going on exactly and what function will be used. I'd say you'd be better off using a subclass and require_once the appropriate subclass.
Assuming not defining the second "a" method is not acceptable, you'll need to move it outside the init method.
It sounds like your require_once call is the problem (definitely should not be called inside the class). Could you post a full sample including your require_once call that isn't working ?
is it possible to do something like this in PHP 5.2.1?
abstract class Test
{
public function __construct()
{
if (function_exists('init')):
$this->init();
}
}
If i try this, the function on the subclass is not called?
You can use method_exists to see if an object has a method with a given name. However, this doesn't let you test what arguments the method takes. Since you're defining an abstract class, simply make the desired method an abstract method.
abstract class Test {
public function __construct() {
$this->init();
}
abstract protected function init();
}
Just be careful you don't call init more than once, and child classes invoke their parents' constructors.
"something like" WHAT exactly?
Anyway, your syntax is totally wrong...
public function __construct()
{
if (function_exists('init')
{
$this->init();
}
}