Can we use $this outside of class. Please look at the example below,
<?php
class Animal {
public function whichClass() {
echo "I am an Animal!";
}
public function sayClassName() {
$this->whichClass();
}
}
class Tiger extends Animal {
public function whichClass() {
echo "I am a Tiger!";
}
public function anotherClass() {
echo "I am a another Tiger!";
}
}
$tigerObj = new Tiger();
//Tiger::whichClass();
$this->anotherClass();
Here I have created new object $tigerObj = new Tiger(); after that I tried to use $this but it throwing error. So is that possible to use $this from outside of the class ? If no,
$this refers to the current object. So why don't we use this ?
Its not possible to use $this in this way, you can create object of that class and then extend the methods which you would like to call. See below ...
class Animal {
public function whichClass() {
echo "I am an Animal!";
}
public function sayClassName() {
$this->whichClass();
}
}
class Tiger extends Animal {
public function whichClass() {
echo "I am a Tiger!";
}
public function anotherClass() {
echo "I am a another Tiger!";
}
}
$tigerObj = new Tiger();
echo $tigerObj->anotherClass();
You will get result "I am a another Tiger!"
$this is impossible to use outside class so you can make static method, and use like this Tiger::anotherClass. Link to doc
class Animal {
public function whichClass() {
echo "I am an Animal!";
}
public function sayClassName() {
$this->whichClass();
}
}
class Tiger extends Animal {
public function whichClass() {
echo "I am a Tiger!";
}
public static function anotherClass() {
echo "I am a another Tiger!";
}
}
$tigerObj = new Tiger();
//Tiger::whichClass();
Tiger::anotherClass();
NO you can't use $this outside the scope of a class
example :
1 $this=new \DateTime();
2 echo $this->format('r');
generates the following error :
Fatal error: Cannot re-assign $this on line 2
Yes it's possible to use $this outside class with php 8.
Example: class.php
<?php
class MyClass {
private $say = '';
public function say(string $text) {
$this->say = $text;
}
public function hear() {
require __DIR__ . '/test.php';
echo $this->say;
}
}
$MyClass = new MyClass();
$MyClass->hear();
?>
test.php
<?php
$this->say('Using this Outside Class Is Possible');
?>
Related
I want to call a function defined in child class from a function defined in the parent class for some logic. I am getting error of undefined function. How can I call this function. Here is my sample code.
<?php
class First
{
public function __construct()
{
echo "First class is initiated.";
}
public function call_child()
{
$this->get_ouput();
}
}
class Second extends First
{
public function __construct()
{
parent::__construct();
}
public function get_output()
{
echo "Here is your output";
}
}
$obj = new Second();
$obj->call_child();
?>
The issue is spelling mistake in your function call name
<?php
class First
{
public function __construct()
{
echo "First class is initiated.";
}
public function call_child()
{
$this->get_output(); //update the name here
}
}
class Second extends First
{
public function __construct()
{
parent::__construct();
}
public function get_output()
{
echo "Here is your output";
}
}
$obj = new Second();
$obj->call_child();
?>
There is a typo when calling the get_output method. However you should define the First class and get_output method as abstract in order to be extended/implemented by the other classes:
abstract class First
{
public function __construct()
{
echo "First class is initiated.";
}
abstract public function get_output();
public function call_child()
{
$this->get_output();
}
}
class Second extends First
{
public function get_output()
{
echo "Here is your output";
}
}
$obj = new Second();
$obj->call_child();
Note: the Second class may not define the constructor if it only calls the parent constructor.
Can I initiate an object instance and call a method inside another method in php?
Please give me examples at this question.. and show me separately all the combinations that can be done with methods and objects.
class Autorizare{
public function user(){
echo "This is a user";
}
}
class Derivata{
function derivata(){
echo "sunt o derivata";
}
$object = new Autorizare();
$object->user();
$object2 = new Derivata();
$object2->derivata();
}
echo $object->user();
echo $object2->derivata();
Something like this..
You can access methods of some class in these ways:
class A {
public function one() {
echo "This is a user";
}
public static function two() {
echo "This is not a user";
}
public function test() {
$this->one(); //for non static methods
self::two(); //for static methods
}
}
class B {
public function test1() {
$a = new A();
$a->one(); //for non static methods
}
public function test2() {
A::two(); //for static methods
}
}
$obj = new B();
$obj->test1();
$obj->test2();
For more details and also how to use scope look at php manual
*edit code upon comment request
Is there a way to call an inherited method, without specifying it's function name?
Something like:
class Child extends Parent {
function some_function(){
// magically inherit without naming the parent function
// it will call parent::some_function()
parent::inherit();
// other code
}
function another_function(){
// it will call parent::another_function()
$result = parent::inherit();
// other code
return $result;
}
}
I could think of a hack to do this using debug_backtrace(), get the last function where inherit() was called and access it's parent with the same function name. I was wondering if there's a nicer way instead of using debug functions which are clearly not meant for this.
You can use the magic __FUNCTION__ constant.
class A
{
function some_function()
{
echo 'called ' . __METHOD__;
}
}
class B extends A
{
function some_function()
{
call_user_func(array('parent', __FUNCTION__));
}
}
$b = new B;
$b->some_function(); // prints "called A::some_function"
Instead of
call_user_func(array('parent', __FUNCTION__));
you can also do
parent::{__FUNCTION__}();
Dirty, but:
class Adult {
function mummy(){
return 'Walk like an Egyptian';
}
function daddy(){
return 'Luke, I am your father';
}
}
class Child extends Adult {
function mummy(){
echo 'Mummy says: ';
$me = explode('::',__METHOD__)[1];
echo parent::$me();
}
function daddy(){
echo 'Daddy says: ';
$me = explode('::',__METHOD__)[1];
echo parent::$me();
}
}
$o = new Child();
$o->mummy();
$o->daddy();
EDIT
Actually giving you a parent method called inherit();
class Adult {
private function mummy(){
return 'Walk like an Egyptian';
}
private function daddy(){
return 'Luke, I am your father';
}
protected function inherit($method) {
$beneficiary = explode('::', $method)[1];
return $this->$beneficiary();
}
}
class Child extends Adult {
public function mummy() {
echo 'Mummy says: ',
parent::inherit(__METHOD__),
PHP_EOL;
}
public function daddy() {
echo 'Daddy says: ',
parent::inherit(__METHOD__),
PHP_EOL;
}
}
$o = new Child();
$o->mummy();
$o->daddy();
Dynamically calling functions:
static::$functionName();
In your case:
$func = __FUNCTION__;
parent::$func();
Note: the function name must be a string, if it's the actual function (not really relevant in this context) then it first needs to be converted to its string name first.
Other stuff that your question will probably lead you towards in the long run.
Check out late static binding it's what you're looking for.
Example taken from the linked page.
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
This is my class code:
class myClass
{
public function myFunc()
{
$myvar = 'Test str';
}
public function result()
{
echo myClass::myFunc()->$myvar;
}
}
and I use this:
$nCls = new myClass;
$nCls->result();
To show Test str form myFunc() but nothing shown. I think the problem is :
echo myClass::myFunc()->$myvar;
Thanks for any help.
You are mixing up quite a few concepts.
First, you have to create a new object of class myClass:
$nCls = new myClass();
Then, you can call the member function (method) on that class:
$nCls->result();
In result(), you just call the other method using $this:
public function result()
{
echo $this->myFunc();
}
Note though that this does nothing. The variable $myvar is local and not a class attribute. I advise you read up on object oriented programming, and object oriented PHP in particular.
class myClass {
public $myvar;
public function myFunc() {
$this->myvar = 'Test str';
return $this;
}
public function result() {
echo $this->myFunc()->myvar;
}
}
$nCls = new myClass;
$nCls->result();
You can do this but this is not a good practice.
The problem is that you declare $myvar only in the scope of method myFunc(). That means it is not visible outside that method. Declare it as a class member instead:
class myClass
{
private $myvar;
public function myFunc()
{
$this->myvar = 'Test str';
}
public function result()
{
echo myClass::myFunc()->$myvar;
}
}
the problem is the scope, you can't call a variable within another function, define a property for the class and set it from a function then retrieve the property with result():
class myClass
{
public $myvar;
public function myFunc()
{
$this->myvar = 'Test str';
}
public function result()
{
echo $this->myvar;
}
}
include "views.php";
class Controller extends views{
function index(){
$this->head();
$this->home();
}
function privacy(){
$this->head();
$this->privc();
}
function about(){
$this->head();
$this->abt();
}
function address(){
$this->head();
$this->add();
}
}
$obj=new Controller();
if(isset($_GET['fun'])){
$obj->$_GET['fun']();
}
else{
$obj->index();
}
This is views.php code
class views{
function head(){
include "views/header.php";
echo "<br>this is header";
}
function abt(){
include "views/about.php";
echo "<br>This is about us page";
}
function home(){
include "views/home.php";
echo "<br>This is Home page";
}
function privc(){
include "views/privacy.php";
echo "<br>This is privacy page";
}
function add(){
include "views/address.php";
echo "<br>This is address page";
}
}
I want to check is a function exists in a library that I am creating, which is static. I've seen function and method_exists, but haven't found a way that allows me to call them in a relative context. Here is a better example:
class myClass{
function test1()
{
if(method_exists("myClass", "test1"))
{
echo "Hi";
}
}
function test2()
{
if(method_exists($this, "test2"))
{
echo "Hi";
}
}
function test3()
{
if(method_exists(self, "test3"))
{
echo "Hi";
}
}
}
// Echos Hi
myClass::test1();
// Trys to use 'self' as a string instead of a constant
myClass::test3();
// Echos Hi
$obj = new myClass;
$obj->test2();
I need to be able to make test 3 echo Hi if the function exists, without needing to take it out of static context. Given the keyword for accessing the class should be 'self', as $this is for assigned classes.
static::class is available since PHP 5.5, and will return the "Late Static Binding" class name:
class myClass {
public static function test()
{
echo static::class.'::test()';
}
}
class subClass extends myClass {}
subClass::test() // should print "subClass::test()"
get_called_class() does the same, and was introduced in PHP 5.3
class myClass {
public static function test()
{
echo get_called_class().'::test()';
}
}
class subClass extends myClass {}
subClass::test() // should print "subClass::test()"
The get_class() function, which as of php 5.0.0 does not require any parameters if called within a class will return the name of the class in which the function was declared (e.g., the parent class):
class myClass {
public static function test()
{
echo get_class().'::test()';
}
}
class subClass extends myClass {}
subClass::test() // prints "myClass::test()"
The __CLASS__ magic constant does the same [link].
class myClass {
public static function test()
{
echo __CLASS__.'::test()';
}
}
class subClass extends myClass {}
subClass::test() // prints "myClass::test()"
Update:
Ahh, apologies. I was temporarily blind :) You'll want to use the magic constant __CLASS__
e.g.
if (method_exists(__CLASS__, "test3")) { echo "Hi"; }
for all situations… the best usage would be…
if method_exist(…) && is_callable(…)
For testing example:
class Foo {
public function PublicMethod() {}
private function PrivateMethod() {}
public static function PublicStaticMethod() {}
private static function PrivateStaticMethod() {}
}
$foo = new Foo();
$callbacks = array(
array($foo, 'PublicMethod'),
array($foo, 'PrivateMethod'),
array($foo, 'PublicStaticMethod'),
array($foo, 'PrivateStaticMethod'),
array('Foo', 'PublicMethod'),
array('Foo', 'PrivateMethod'),
array('Foo', 'PublicStaticMethod'),
array('Foo', 'PrivateStaticMethod'),
);
foreach ($callbacks as $callback) {
var_dump($callback);
var_dump(method_exists($callback[0], $callback[1])); // 0: object / class name, 1: method name
var_dump(is_callable($callback));
echo str_repeat('-', 40), "n";
}
Source here