calling method in another class in php - 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

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();

PHP OOP , How to assign not static property to static method?

could someone explain how to use not static property in static method in php, this is wrong code, but i want to know how to fix this, thank you
<?php
class SomeClass
{
public $_someMember;
public function __construct()
{
$this->_someMember = 1;
}
public static function getSomethingStatic()
{
return $this->_someMember * 5; // here's the catch
}
}
echo SomeClass::getSomethingStatic();
?>
You can't directly. You need to create an object instance. You can make one and pass it to a static method, or make one in static method's body.
Regular (non-static) properties require object instance of given class (type).
Static methods are called by referring to the class itself, not an object.
You can however use static properties or constants for static methods needs without creating object instance at all.
You have to instantiate object
<?php
class SomeClass
{
public $_someMember;
public function __construct()
{
$this->_someMember = 1;
}
public static function getSomethingStatic()
{
$object = new self();
return $object->_someMember * 5; // here's the catch
}
}
echo SomeClass::getSomethingStatic();
You can statically create an instance of the class that the method is being called on via:
$instance = new static();
You can also statically create instances of the class that actually defines the method via:
$instance = new self();
As an example, take these classes First and Second.
class First
{
public static function getStatic()
{
return new static();
}
public static function getSelf()
{
return new self();
}
}
class Second extends First{ }
When we use Second::getStatic(), we will get an instance of Second.
When we use Second::getSelf(), we will get an instance of First.
When we call either method via First, we will get an instance of First.
This means you can change your method to:
public static function getSomethingStatic()
{
$instance = new static(); // or new self() if you always want to use 'SomeClass'
// and never an extending class.
return $instance->_someMember;
}

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
}

PHP get static methods

i want to call a class method by a var (like this):
$var = "read";
$params = array(...); //some parameter
if(/* MyClass has the static method $var */)
{
echo MyClass::$var($params);
}
elseif (/* MyClass hat a non-static method $var */)
{
$cl = new MyClass($params);
echo $cl->$var();
}
else throw new Exception();
i read in the php-manual how to get the function-members of a class (get_class_methods). but i get always every member without information if its static or not.
how can i determine a method´s context?
thank you for your help
Use the class ReflectionClass:
On Codepad.org: http://codepad.org/VEi5erFw
<?php
class MyClass
{
public function func1(){}
public static function func2(){}
}
$reflection = new ReflectionClass('MyClass');
var_dump( $reflection->getMethods(ReflectionMethod::IS_STATIC) );
This will output all static functions.
Or if you want to determine whether a given function is static you can use the ReflectionMethod class:
On Codepad.org: http://codepad.org/2YXE7NJb
<?php
class MyClass
{
public function func1(){}
public static function func2(){}
}
$reflection = new ReflectionClass('MyClass');
$func1 = $reflection->getMethod('func1');
$func2 = $reflection->getMethod('func2');
var_dump($func1->isStatic());
var_dump($func2->isStatic());
One way I know of is to use Reflection. In particular, one would use ReflectionClass::getMethods as such:
$class = new ReflectionClass("MyClass");
$staticmethods = $class->getMethods(ReflectionMethod::IS_STATIC);
print_r($staticmethods);
The difficulty of this is that you need to have Reflection enabled, which it is not by default.

PHP: using $this in constructor

I have an idea of using this syntax in php. It illustrates that there are different fallback ways to create an object
function __construct() {
if(some_case())
$this = method1();
else
$this = method2();
}
Is this a nightmare? Or it works?
Or it works?
It doesn't work. You can't unset or fundamentally alter the object that is being created in the constructor. You can also not set a return value. All you can do is set the object's properties.
One way to get around this is having a separate "factory" class or function, that checks the condition and returns a new instance of the correct object like so:
function factory() {
if(some_case())
return new class1();
else
return new class2();
}
See also:
Breaking the constructor
PHP constructor to return a NULL
Why not to do something more common like:
function __construct() {
if(some_case())
$this->construct1();
else
$this->construct2();
}
You can just create class methods method1 and method2 and just write
function __construct() {
if(some_case())
$this->method1();
else
$this->method2();
}
You can make factory method.
Example:
class A {}
class B {}
class C {
function static getObject() {
if(some_case())
return new A();
else
return new B();
}
}
$ob = C::getObject();
It sounds a little bit like the Singleton class pattern.
See #Ivan's reply among others for the correct syntax for what it looks like you're trying to do.
However, there are is another alternative - use a static method as an alternative constructor:
class myclass {
function __construct() { /* normal setup stuff here */}
public static function AlternativeConstructor() {
$obj = new myclass; //this will run the normal __construct() code
$obj->somevar = 54; //special case in this constructor.
return $obj;
}
}
...
//this is how you would use the alternative constructor.
$myobject = myclass::AlternativeConstructor();
(note: you definitely can't use $this in a static method)
If you want to share some functions, do some like
class base{
'your class'
}
class A extends base{
'your class'
}
class B extends base{
'your class'
}
And call like
if(some_case())
$obj = new A();
else
$obj = new B();

Categories