class Test extends Parent {
$a = 1;
public function changeVarA() {
$a = 2;
return parent::changeVarA();
}
}
Can Anyone please explain what does return parent::function(); it do ?
Thank you...! ;D
This will call the function changeVarA in the parent class.
When a class extends another class, and both have the same function name, the parent:: call forces the parent version of the function to be called and used. The return part of it will simply return whatever the parent function returns after it completes:
<?php
class A {
function example() {
echo "Hello Again!\n";
}
}
class B extends A {
function example() {
echo "Hello World\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?>
output:
Hello World
Hello Again!
The example is taken from the PHP documentation which you really should take a look at.
Related
Iam learning php these days. I have one query below:
class A {
var $a;
}
class B extends A{
var $b = $a; //here its showing me error, i even tried as '$this->$a' but still showing error. so, how do I use $a in class B? ( instead of using in a function ),
}
I am declaring $b just inside class instead of inside a function because I need to use $b variable in many places inside my php file.
So, please tell me how to fix this.
try like below
<?php
class firstname
{
public static $name='Your First Name';
}
class lastname
{
public static $last='Your Last Name';
}
class Fullname
{
public static function staticValue() {
return firstname::$name."--".lastname::$last;
}
}
print Fullname::staticValue() . "\n";
?>
hope it will help you
1.) use public instead of var
2.) when you extending a class, you have got access to properties of this parent. So you don't need to declare $b, you can just use $this->a
class a {
$a = 'test';
}
class b extends a {
public function get() {
echo $this->a;
}
}
$b = new b;
$b->get(); // prints test
I'm new to programming. I have this going on:
I have Class A, which have many functions. One of those functions is functionX.
In functionX I need to make a call to functionY which belongs to another class: Class B.
So how do I acces to functionY from inside functionX?
I use Codeigniter.
Thanks in advance.
Try and experiment with this.
class ClassA {
public function functionX() {
$classB = new ClassB();
echo $classB->functionY();
}
}
class ClassB {
public function functionY() {
return "Stahp, no more OO, stahp!";
}
}
Class function? A static method?
If you have an instance (public) method, you just call $classB->functionY().
If you have a static method, you would call ClassB::functionY();
So:
class ClassA {
public function functionX(){
$classB = new ClassB();
// echo 'foo';
echo $classB->functionY();
// echo 'bar';
echo ClassB::functionYStatic();
}
}
class ClassB {
public $someVar;
public static $someVar2 = 'bar';
function __construct(){
$this->someVar = 'foo';
}
public function functionY(){
return $this->someVar;
}
public static function functionYStatic(){
return self::$someVar2;
}
}
Well that depends. If that function is a static function or not.
First off you must include the file with the class...
include_once('file_with_myclass.php');
If it is static you can call it like this:
ClassName::myFunction()
If it is not, then you create an instance of the class and then call the function on that instance.
$obj = new ClassName();
$obj->myFunction();
As you can guess the function being static means you can call it without the need of creating an instance. That is useful for example if you have a class Math and want to define a function that takes to arguments to calculate the sum of them. It wouldn't really be useful to create an instance of Math to do that, so you can declare as static and use it that way.
Here's a link to the docs with further info
http://www.php.net/manual/en/keyword.class.php
If functionY is static you can call ClassB::functionY(). Else you must create instance of Class B first. Like:
$instance = ClassB;
$instance->functionY();
But maybe you mean something else?
Looks like one of your class has a dependency to another one:
<?php
class A
{
public function x()
{
echo 'hello world';
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function y()
{
$this->a->x();
}
}
$a = new A();
$b = new B($a);
$b->y();
Depending how your code looks like, if it makes sense, you can inject class A into y()
public function y(A $a)
{
// your code with $a
}
I would like to display a parent Class variable, I can't find a way to solve the situtation...
Here is my PHP :
class A {
public $a;
}
class B extends A {
public function __construct() {
echo $parent->a;
}
}
$B = new B();
This is supposed to output $a, in my case $a is an PDO object, and instead of print it, i call a prepare() on it :)
like that :
class A {
public $a;
}
class B extends A {
public function __construct() {
$this->a->prepare('random SQL request');
}
}
$B = new B();
I have a "Cannot access empty property" PHP error
Thanks !
echo $this->a;
Many times the comments in the PHP manual are as valuable as the manual itself:
http://www.php.net/manual/en/keyword.parent.php#42153
Something like this would work:
class A {
public $a = "Hello World";
}
class B extends A {
public function __construct() {
echo $this->a;
}
}
$B = new B();
Run it:
php parent.php
Hello World
I code something like this to give you an example
This is using "$this->"
<?php
class A{
public function example(){
echo "A";
}
}
class B extends A{
public function example2(){
$this->example();
}
}
$b = new B();
echo $b->example2();
?>
and This is using parent::
<?php
class A{
public function example(){
echo "A";
}
}
class B extends A{
public function example2(){
parent::example();
}
}
$b = new B();
echo $b->example2();
?>
What is different between $this-> and parent:: in OOP PHP?
The difference is that you can access a function of a base class and not of the currient implementation.
class A {
public function example() {
echo "A";
}
public function foo() {
$this->example();
}
}
class B extends A {
public function example() {
echo "B";
}
public function bar() {
parent::example();
}
}
And here some tests:
$a=new A();
$a->example(); // echos A
$a->foo(); // echos A
$b=new B();
$b->example(); // echos B
$b->foo(); // echos B
$b->bar(); // echos A
parent::example() calls the parent class method, where $this->example() call the current class method.
In your example there's no difference, since class B doesn't override example() method. It is common to write something like this (maybe it will help you to understand better this concept):
class A {
public function example(){
echo 'A';
}
}
class B extends A {
public function example(){
echo 'B';
}
public function example2(){
$this->example();
}
public function example3() {
parent::example();
}
}
$b = new B();
$b->example2();//print B
$b->example3();//print A
In simple words
$this is an instance reference, so whenever you use $this it starts referencing current class methods and properties.
parent is a parent reference which can be used to access parent class properties and methods with public or protected access modifier.
parent:: will call a method or an attribute of the parent. However, since this is refering to the class and not any kind of instance, you can only call a static method or attribute.
$this-> refers to the current instance of the object you call this in.
You could also want to refer to self:: which refers to the current class (once again, no instance involved here) within an object or a static method.
Is something like the following possible in PHP?
$blah = 'foo1';
class foo2 extends $blah {
//...
}
class foo1 {
//...
}
This gives an error.
I want to dynamically set $blah so I can extend whatever class I want.
Edit: The reason for wanting to do this because I wanted to use a function out of another class in a related class. In the end it would have been something like:
Final extends foo1 extends foo2 extends foo3 extends foo4 extends parent { ... }
In the end I decided to instantiate the other class within the class and use it. Not the best options because they both you 2 of the same classes, but this won't be used that often, so it will work for now.
You're assuming here php executes top to bottom, but it doesn't quite work like that:
<?php
foo(); # works
function foo(){
print "bar";
}
<?php
foo(); #dies
if( $i == 1 )
{
function foo(){
print "bar";
}
}
<?php
$i = 1;
if( $i == 1 )
{
function foo(){
print "bar";
}
}
foo(); #works
Now, although you can conditionally create classes:
<?php
class A { }
class B { }
if( false ){
class C extends B {
public static function bar(){
print "baz";
}
}
}
C::bar(); # dies
You cant instantiate one at runtime from a variable:
<?php
class A { }
class B { }
$x = 'B';
if( false ){
class C extends $x {
public static function bar(){
print "baz";
}
}
}
C::bar();
---> Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in /tmp/eg.php on line 7
There is a way to do it with Eval, but you really don't want to go there:
<?php
class A { }
class B { }
$x = 'B';
if( true ){
$code =<<<EOF
class C extends $x {
public static function bar(){
print "baz";
}
}
EOF;
eval( $code );
}
C::bar();
$o = new C;
if ( $o instanceof $x )
{
print "WIN!\n";
}
--->barWIN!
However, there is a more important question here:
Why the hell would you want to extend a different class at runtime
Anybody using your code will want to hold you down and whip you for that.
( Alternatively, if you're into whipping, do that eval trick )
I know this question was asked a long time ago, but the answer is relatively simple.
Assuming you want to extend class foo if class foo exists, or class bar if it doesn't, you'd use:
if(!class_exists('foo')) {
class foo extends bar {
function __construct() {
parent::__construct();
}
}
}
class myclass extends foo{
//YOUR CLASS HERE
}
Using PHP overloading you can accomplish this to a certain extent.
class variable_class {
public $orginalBaseClass;
public $orginalArgs;
public function __construct() {
// Get constructor parameters.
$this->orginalArgs = func_get_args();
// Get class name from args or 3rd party source.
$classname = 'stdClass';
// Pass along args to new class.
$this->orginalBaseClass = new $classname($this->orginalArgs);
}
public function __call($name, $arguments) {
// Pass all method calls to the orginalBaseClass.
return call_user_func_array(array($this->orginalBaseClass, $name), $arguments);
}
}
I'm using this pattern inside a Drupal module for prefetching data from the cache.
I don't see how this would be particularly useful, but to answer your question... no. There's no way to dynamically do that because the generated class has to be instantiated before the variable is evaluated (if that makes sense).
To put it simply: The class must exist before the code can be properly executed.
If you don't have too many values for $blah, you could extend each one in a different file then require_once "classes/foo_$blah.php"
Otherwise, you're stuck with the eval() solution... good luck with that... :)
I assume that this is for ease-of-maintenance, right? Extending a class at run time really is pretty crazy.
class SuperClassOne { /* code */ }
class SuperClassTwo { /* code */ }
class IntermediateClass extends SuperClassOne { /* empty! */ }
class DescendantClassFoo extends IntermediateClass{ }
class DescendantClassBar extends IntermediateClass{ }
class DescendantClassBaz extends IntermediateClass{ }
Then, when you want to change all your DescendantClass* classes, you just have to change what the IntermediateClass extends:
class IntermediateClass extends SuperClassTwo { }
I tested something with defines and barking:
<?php
define("INHERIT",A);
class A{
public function bark(){
return "I'm A";
}
}
class B{
public function bark(){
return "I'm B";
}
}
class C extends INHERIT{}
//main?
$dog = new C();
echo $dog->bark();
?>
the output is:
Fatal error: Class 'INHERIT' not found
in D:\sites\inherit.php on line 15
so the answer for "are variable class extensions possible?" is: No.
you should have tried $$
$blah = 'foo1';
class foo2 extends $$blah {
//...
}
class foo1 {
//...
}