PHP: Extending Classes - php

I'm absolutely sure this has been asked before, but I cannot find it anywhere.
So I have two classes. A and B
class classA
{
public $var1;
public $classbVar;
public function init()
{
// This is here because other script is run before it is called
// in the live code.
// it basically checks that the file exists. There is a reason for this.
if (file_exists('classB.php'))
{
require_once('classB.php');
}
else
{
echo "An error has occurred loading the second class.";
}
$this->var1 = "something";
$this->classbVar = new classB
echo $this->classbVar->doSomething();
}
}
In a separate file
class classB extends classA
{
public function doSomething()
{
echo $this->var1;
}
}
In a third file, I'm calling classA and running the init function. This is not real code, but identical to what I have written.
So why doesn't this work. if I VAR_DUMP I get null.... What have I done wrong or misunderstood?
LET ME BE MORE CLEAR:
There is a third file which calls classA as below;
require_once('classA.php')
$classA = new classA;
$classA->init();
My apologies for any confusion, I did this on the fly a little bit, as I am sure I am missing something simple here. Surely the way I am trying to do this will work somehow.

There are 2 problems here that cause your output to be null:
You are generating a new $classA object and any values you set on that, will not automatically be set on the $classbVar object as that is a completely different object of a class that just extends the A class, not the $classA object you have just generated. With the exception of a static property of course...
If you want to set the value of a property in an object, you need $this->var1 instead of $var1. Note if you set the value in your $classA object, it is still not set for the $classbVar object.

Put require_once above class declaration (this is not big issue but it's more clear)
Assign variables to class properties because they way you did the scope of them is only within the method.
$var1 = "something";
should be changed to
$this->var1 = "something";
Also the class values are not shared unless they are declared as static. So to access the properties from parent class you can do following:
class classA
{
public $var1;
public function init()
{
$this->var1 = "something";
}
}
// other file
require_once("A class location");
class classB extends classA
{
public function doSomething()
{
echo $this->var1;
}
}
$b = new classB();
$b->init();
$b->doSomething();
or more clean way:
class A
{
protected $var1;
public function __construct()
{
$this->var1 = "something";
}
}
// other file
require_once("A class location");
class B extends A
{
public function doSomething()
{
return $this->var1;
}
}
$b = new B();
echo $b->doSomething();
// or shorter syntax
echo {new B()}->doSomething();
Instead of using require_once() it's better to use PSR-4 autoloader.

Related

PHP OOP - Accessing property value is returning empty

I have the following class, and for some reason it's not accessing the test property. Why is this? I'm new to OOP, so please be easy on me. Thanks
class Test {
private $test;
function __contruct() {
$this->test = "test";
}
static function test() {
echo $this->test;
}
}
$test = new Test;
$test::test();
Because static methods are callable without an instance of the object
created, the pseudo-variable $this is not available inside the method
declared as static.
PHP Documentations.
Good morning.
It seems you have 3 issues with your code.
There is a syntax error at constructor line change it from __contruct to __construct.
Change test function visibility to public
Access your function with the -> instead of ::
To elaborate further on the above answers: Static methods and variables are not linked to any particular instance of the object, this is why you have to call test with $test::test(). This also means that you cannot access an instance variable from without a static method and it doesn't really make sense to do so (If you had multiple instances of the object with different values set for that variable, how would the interpreter know which instance/value to use?)
If you want to have a field accessible from a static method then you have to make the field static as well. So, if you wanted to have $test accessible from your static method test() then you'd have to write your function as something along these lines:
class Test {
private static $test;
function __contruct() {
Test::$test = "test";
}
public function test() {
echo Test::$test;
}
}
$test = new Test;
$test::test();
However, it doesn't really make sense to be initialising a static field like that in your constructor. So you'd more likely be wanting to do something like:
class Test {
private static $test = "test";
function __contruct() {
}
public static function test() {
echo Test::$test;
}
}
$test = new Test;
$test::test();
Or, if you don't actually require test() to be static then you could just make it an instance method:
class Test {
private $test = "test";
function __contruct() {
$this->$test = "test"
}
public function test() {
echo $this->$test;
}
}
$test = new Test;
$test->test();

calling method in another class in php

I am new to php and trying to call a function in another class.
How do I call function1 and function2 in class xyz???
class abc {
private $lmn = "lmn";
private $say1;
private static $static;
private function __construct(){
$say1 = print $this->lmn;
}
public static function1(){
$static = "YEAAHHHH";
}
public function function2(){
return $this->say1;
}
file 2:
require 'abc.php';
class xyz {
/**
* $e = new xyz();
*
*/
$e = xyz:: function1();// error
$d = xyz:: function 2(); //error
}
Also under what circumstance I should use
$obj = new class();
$obj->functionname();
and
$obj = class::functionname();
You have 2 different types of methods here, static and non-static.
To call the static (function1())
You don't need to instantiate the class, as it's static.
class zyx {
public function foo() {
return abc::function1();
}
}
To call the non-static (function2())
You need to instantiate the class, as it's not static.
class zyx {
public function foo() {
$abc = new abc();
return $abc->function2();
}
}
You would call function1 like:
abc::function1();
It is a method in abc not xyz.
function2() you would only call if you had an instance of abc because it is an instance method and not a static method. I.e.
$abc = new abc();
$abc->function2();
Static functions are intended to be called on classes, instance methods (i.e. function2() are intended to be called on instances of classes. I would recommend reading http://php.net/manual/en/oop5.intro.php.
Static functions can be called without instantiating your class...
$myClass::function1();
Non-static functions need to be instantiated first:
$myClass = new abc();
$myClass->function2();
So in your example:
require 'abc.php';
class xyz {
public function CallFunc1()
{
abc::function1();
}
public function CallFunc2()
{
$myClass = new abc();
$myClass->function2();
}
}
require 'abc.php';
class xyz {
public function static(){
return abc:: function1();// this is a static function
}
public function nonstatic(){
$e = new abc();
return $e->function2();
}
}
First of all, you can't have a space between function and 2():
$d = xyz::function2(); //correct
$d = xyz::function 2(); //very incorrect
I was going to have a second of all, but #hd beat me to it.
I think you have messed up with the code. I can share something with something that I found very helpful as an answer for your second question. Spend a bit time reading this. This is very basic, simple and well guided.
http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762

calling a class function from another class function

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
}

Call function in function from another class PHP

I have read a few threads about abstract class here at Stackoverflow and I think it's what I need, but I can't get the declaration straight.
What I want to do is to call a function2 (in classB) in a function1 (in classA).
How should I do this?
If you only need to access ClassB's method from ClassA but don't need a parent-child relationship between the two, a static method may be more appropriate:
class ClassA
{
public function method1() {
echo ClassB::method2();
}
}
class ClassB
{
public static function method2() {
return 'WOOT!';
}
}
$cls_a = new ClassA();
$cls_a->method1();
// or alternatively, you don't even need to instantiate ClassA
echo ClassB::method2();

Instantiating classes and accessing methods from different classes

I'm trying to use a Class_B function in one of Class_A's functions. But a lot of Class_B's functions include $this which causes problems. These are both classes (each class is of course in its own file):
class Class_A
{
function hello()
{
require('class_b.php');
echo 'Hello ' . Class_B::person();
}
function bye()
{
require('class_b.php');
echo 'Bye ' . Class_B::person();
}
}
class Class_B
{
function person()
{
// various operations and variables
echo $this->get_user($id);
}
}
When I run the Class_A file I get Call to undefined method Class_A::person() in (...) because I think the $this value is changed when I instantiate the Class_A class. It overrules the Class_B value. How can I stop this?
Also, another question: how can I access Class_B from every function in Class_A? I don't want to redeclare the class. Do I need to do this:
class Class_A
{
function function1()
{
require('class_b.php');
$class_b = new Class_B();
// code
}
function function2()
{
require('class_b.php');
$class_b = new Class_B();
// code
}
}
Or do I need to use a constructor or something?
By Class_B::person() you are calling the method statically. So you should declare the person() method as static and can't use $this because you don't have an instance of Class_B.
If you need an instance of Class_B, just create it and store in the class_B on construction.
class Class_A {
private $b;
function __construct()
{
$this->b = new Class_B();
}
function stuff()
{
$this->b->person();
}
Don't put require inside a method. Code in an included file inherits the scope of the place where you include it, and in your example, bad things happen. Also, for class definition scripts, consider require_once instead of require, to avoid multiple definitions.
As a rule of thumb, put all includes and requires at the top of your script. Better yet, set up a class autoloader, and register it in an auto_prepend script. That way, you won't have to manually include anything at all (at least not for class definitions).
What you might want is dependency injection, whereby you pass an object of Class_B into Class_A's constructor and hold it as a property in Class_A. It then becomes available in Class_A as $this->classB or similar.
// Include Class_B code outside the class.
require_once('class_b.php');
class Class_A {
// Property to hold Class_B
public $b;
// Constructor
public function __construct($b) {
$this->b = $b;
}
public function function1(){
// code
$this->b;
}
public function function2(){
// code
$this->b;
}
}
// Now call your objects:
// The Class_B which will be injected into A
$b = new Class_B();
// Your Class_A, which holds an instance of Class_B as a property
$a = new A($b);

Categories