简体   繁体   English

我可以/如何...在 PHP 中的类之外调用受保护的函数

[英]Can I/How to... call a protected function outside of a class in PHP

I have a protected function that is defined within a certain class.我有一个在某个类中定义的受保护的函数。 I want to be able to call this protected function outside of the class within another function.我希望能够在另一个函数的类之外调用这个受保护的函数。 Is this possible and if so how may I achieve it这可能吗,如果可以,我该如何实现

class cExample{

   protected function funExample(){
   //functional code goes here

   return $someVar
   }//end of function

}//end of class


function outsideFunction(){

//Calls funExample();

}

Technically, it is possible to invoke private and protected methods using the reflection API.从技术上讲,可以使用反射 API 调用私有和受保护的方法。 However, 99% of the time doing so is a really bad idea.然而,在 99% 的情况下这样做是一个非常糟糕的主意。 If you can modify the class, then the correct solution is probably to just make the method public.如果您可以修改类,那么正确的解决方案可能是将方法设为公开。 After all, if you need to access it outside the class, that defeats the point of marking it protected.毕竟,如果您需要在类之外访问它,那就失去了将其标记为受保护的意义。

Here's a quick reflection example, in case this is one of the very few situations where it's really necessary:这是一个快速反射示例,以防这是真正必要的极少数情况之一:

<?php
class foo { 
    protected function bar($param){
        echo $param;
    }
}

$r = new ReflectionMethod('foo', 'bar');
$r->setAccessible(true);
$r->invoke(new foo(), "Hello World");

That's the point of OOP - encapsulation:这就是 OOP 的重点——封装:

Private私人

Only can be used inside the class. Not inherited by child classes.

Protected受保护

Only can be used inside the class and child classes. Inherited by child classes.

Public公众号

Can be used anywhere. Inherited by child classes.

If you still want to trigger that function outside, you can declare a public method that triggers your protected method:如果您仍然想在外部触发该函数,您可以声明一个触发受保护方法的公共方法:

protected function b(){

}

public function a(){
  $this->b() ;
  //etc
}

You can override this class with another where you make this public.你可以用另一个你公开的类来覆盖这个类。

class cExample2 extends cExample {
  public function funExample(){
    return parent::funExample()
  }
}

(note this won't work with private members) (请注意,这不适用于私人成员)

But the idea of private and protected members is to NOT BE called from outside.但是私有成员和受保护成员的想法是不能从外部调用的。

If you want to share code between your classes you can use traits, but it depends how you want use your function/method.如果你想在你的类之间共享代码,你可以使用特征,但这取决于你想如何使用你的函数/方法。

Anyway反正

trait cTrait{
   public function myFunction() {
      $this->funExample();
   }
}

class cExample{
   use cTrait;

   protected function funExample() {
   //functional code goes here

   return $someVar
   }//end of function

}//end of class

$object = new cExample();
$object->myFunction();

This will work, but keep in mind that you don't know what your class is made of this way.这会起作用,但请记住,您不知道您的类是由这种方式构成的。 If you change the trait then all of your classes which use it will be altered as well.如果您更改特性,那么所有使用它的类也将被更改。 It's also good practice to write an interface for every trait you use.为您使用的每个特征编写一个接口也是一种很好的做法。

here i can give you one example like below在这里我可以给你一个像下面这样的例子

<?php
    class dog {
        public $Name;
        private function getName() {
            return $this->Name;
        }
    }

    class poodle extends dog {
        public function bark() {
            print "'Woof', says " . $this->getName();
        }
    }

    $poppy = new poodle;
    $poppy->Name = "Poppy";
    $poppy->bark();
?>

or one another way to use with latest php或另一种与最新 php 一起使用的方法

In PHP you can do this using Reflections.在 PHP 中,您可以使用反射来做到这一点。 To invoke protected or private methods use the setAccessible() method http://php.net/reflectionmethod.setaccessible (just set it to TRUE)要调用受保护或私有方法,请使用 setAccessible() 方法http://php.net/reflectionmethod.setaccessible (只需将其设置为 TRUE)

If the parent's method is protected, you can use an anonymous class:如果父方法受保护,则可以使用匿名类:

class Foo {
    protected function do_foo() {
        return 'Foo!';
    }
}

$bar = new class extends Foo {
    public function do_foo() {
        parent::do_foo();
    }
}

$bar->do_foo(); // "Foo!"

https://www.php.net/manual/en/language.oop5.anonymous.php https://www.php.net/manual/en/language.oop5.anonymous.php

Another option (PHP 7.4)另一种选择(PHP 7.4)

<?php
class cExample {
   protected function funExample(){
       return 'it works!';
   }
}

$example = new cExample();

$result = Closure::bind(
    fn ($class) => $class->funExample(), null, get_class($example)
)($example);

echo $result; // it works!

I am using Laravel.我正在使用 Laravel。 i was facing issue while access protected method outside of class .我在课堂外访问受保护的方法时遇到了问题。

   $bookingPriceDetails = new class extends BookingController {
        public function quotesPrice( $req , $selectedFranchise) {
           return parent::quotesPrice($req , $selectedFranchise);
        }
    };

     return $bookingPriceDetails->quotesPrice($request , selectedFranchisees());

here BookingController is Class name from which i want to get protected method.这里BookingController是我想从中获取protected方法的名。 quotesPrice( $req , $selectedFranchise) is method that i want to access in different Class. quotesPrice( $req , $selectedFranchise)是我想在不同的类中访问的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM