【问题标题】:Is it possible to declare a method static and nonstatic in PHP?是否可以在 PHP 中声明静态和非静态方法?
【发布时间】:2012-07-05 02:34:09
【问题描述】:

我可以将对象中的方法声明为调用静态方法的同名静态和非静态方法吗?

我想创建一个具有静态方法“发送”和调用静态函数的非静态方法的类。例如:

class test {
    private $text;
    public static function instance() {
        return new test();
    }

    public function setText($text) {
        $this->text = $text;
        return $this;
    }

    public function send() {
        self::send($this->text);
    }

    public static function send($text) {
        // send something
    }
}

我希望能够调用这两个函数上的函数

test::send("Hello World!");

test::instance()->setText("Hello World")->send();

有可能吗?

【问题讨论】:

  • 如果我可以问你为什么要这样做?
  • 很多人热衷于将其视为一个糟糕的问题,只是因为他们个人想不出它的用途。这是一个例子:我需要这个,因为我想提供一些事件处理函数。我想提供 SomeClass::on('some_event',$handler_fn) ,它将应用于 SomeClass 的每个实例,以及 $instance->on('some_event',$handler_fn) ,它仅适用于特定实例。所以,好问题,感谢@lonesomeday 的正确答案,没有任何无知的判断。
  • 很多人认为只有 PHP,也许尝试一些其他语言,如 ruby​​ 和 python 会有所帮助!

标签: php oop


【解决方案1】:

可以做到这一点,但这有点棘手。您必须通过重载来做到这一点:the __call and __callStatic 魔术方法。

class test {
    private $text;
    public static function instance() {
        return new test();
    }

    public function setText($text) {
        $this->text = $text;
        return $this;
    }

    public function sendObject() {
        self::send($this->text);
    }

    public static function sendText($text) {
        // send something
    }

    public function __call($name, $arguments) {
        if ($name === 'send') {
            call_user_func(array($this, 'sendObject'));
        }
    }

    public static function __callStatic($name, $arguments) {
        if ($name === 'send') {
            call_user_func(array('test', 'sendText'), $arguments[0]);
        }
    }
}

这不是一个理想的解决方案,因为它会使您的代码更难遵循,但只要您的 PHP >= 5.3,它就可以工作。

【讨论】:

  • 这让我的眼睛 b̢̗̫͕l͓̫͈e҉͍̖͙ḙ̣̭̦̫̞͟d̼。我不会投反对票,因为你已经警告过他这种编码不会让他的生活变得轻松,而且它很有帮助。但还是:
  • @lonesomeday 投票只是因为你有耐心写出几乎没有实际用途的代码!还回答了问题:-)
  • @Truth 是的。应该是“你可以这样做,但你真的不应该这样做。”
  • 感谢您的回答.. 确实,这个解决方案对于另一个人来说并不容易遵循.. 所以我不会使用它.. 但它可以解决我的问题,非常感谢
  • 你们都说这是个坏主意,但是如果你有一个你希望能够作为会员使用的功能以获得访问权限,那么做这样的事情不是有用且更容易吗成员变量和另一个具有相同目的但您可以使用自己的参数的变量?当然,您可以只使用函数的实例来获取变量,但想象它们是私有的。它应该对例如数学有用,它在不需要类的实例以及需要的情况下很有用。没有混淆和更快的编码。否则可以使用 cmets。 :D
【解决方案2】:

我将创建一个隐藏类作为构造函数,并在父类中返回该隐藏类,该隐藏类的静态方法等于隐藏类方法:

// Parent class

class Hook {

    protected static $hooks = [];

    public function __construct() {
        return new __Hook();
    }

    public static function on($event, $fn) {
        self::$hooks[$event][] = $fn;
    }

}


// Hidden class

class __Hook {

    protected $hooks = [];

    public function on($event, $fn) {
        $this->hooks[$event][] = $fn;
    }

}

静态调用:

Hook::on("click", function() {});

动态调用它:

$hook = new Hook;
$hook->on("click", function() {});

【讨论】:

  • 你的隐藏类没有任何作用,它总是调用静态方法。(在 php 版本 5.3.0 - 7.4.1 中测试)@see: 3v4l.org/HIBKR
【解决方案3】:

不,你不能有两个同名的方法。您可以通过重命名其中一种方法来完成基本相同的操作。将 test::send("Hello World!"); 重命名为 test::sendMessage("Hello World!"); 会起作用。我只需创建一个带有可选文本参数的发送方法,该参数会更改方法的功能。

public function send($text = false) {
    if (!$text) {
        $text = $this -> text;
    }

    // Send something
}

我很想知道你为什么需要静态函数。

【讨论】:

  • 重命名静态方法绝对是明智的做法。
【解决方案4】:

我同意不惜一切代价避免这种情况,但在某些情况下它可能有用。

在大多数情况下,它只会使您的代码不可读和难以管理。

相信我,我一直在走这条路。

这是一个可能仍然可行的用例场景示例。

我将 CakePHP 3.0 的 File 类扩展为我的默认文件处理类。

我想要一个静态 mime 类型猜测器。

在某些情况下,我有一个文件名而不是实际文件,在这种情况下需要做出一些假设。 (如果文件存在,尝试从中获取 mime,否则使用提供的文件名扩展)

其他时候,如果我实际实例化了一个对象,默认的 mime() 方法应该可以工作,但如果它失败了,则需要从对象中提取文件名,而应该调用静态方法。

为避免混淆,我的目标是通过调用相同的方法来获取 mime 类型:

静态:

NS\File::type('path/to/file.txt')

作为对象

$f = new NS\File('path/to/file.txt');
$f->type();

这是我的扩展类示例:

<?php

namespace NS;

class File extends \Cake\Utility\File
{

    public function __call($method, $args) {
        return call_user_func_array([get_called_class(), 'obj'.ucfirst($method)], $args);
    }
    public static function __callStatic($method, $args) {
        return call_user_func_array([get_called_class(), 'static'.ucfirst($method)], $args);
    }

    public function objType($filename=null){
        $mime = false;
        if(!$filename){
            $mime = $this->mime();
            $filename = $this->path;
        }
        if(!$mime){
            $mime = static::getMime($filename);
        }
        return $mime;
    }

    public static function staticType($filename=null){
        return static::getMime($filename);
    }

    public static function getMime($filename = null)
    {
        $mimes = [
            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'ctp' => 'text/html',
            'twig' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',
            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',
            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',
            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',
            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',
            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',
            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        ];
        $e = explode('.', $filename);
        $ext = strtolower(array_pop($e));
        if (array_key_exists($ext, $mimes)) {
            $mime = $mimes[$ext];
        } elseif (function_exists('finfo_open') && is_file($filename)) {
            $finfo = finfo_open(FILEINFO_MIME);
            $mime = finfo_file($finfo, $filename);
            finfo_close($finfo);
        } else {
            $mime = 'application/octet-stream';
        }
        return $mime;
    }
}

【讨论】:

    【解决方案5】:

    在 php 中,您可以设置/分配具有方法可见性(Public、Private、Protected)的类方法以及类属性,它可以声明类方法或类属性的限制分布,例如可以在类外部访问或不是..

    为了调用目的,我们有两个方法,

    1. 静态 (self::)
    2. 非静态 ($this->)

    让一个类 Foo 有一些方法和属性.. 哪些有可见性和调用方法

        <?php
    
        class Foo {
    
         public const WELCOME ='This is WELCOME Non Static Constant For Foo Class';
        public string $text='This is A Text Non Static Foo Class Properties';
        public static string $texter='This is A Texter Foo Static Class Properties';
        private string $ptext='This is a private string Non Static properties of Class Foo';
          
        
        public static function Bar()
        {
            echo "Static Method Bar is calling\n";
        }
        
        public function Baz()
        {
            echo "Non Static Method Baz is calling \n";
        }
        
        
        protected function Another()
        {
            echo "Non Static Method Another is calling \n";
        }
        
        private function Again()
        {
            echo "Non Static Private Method Again is calling \n";
        }
        
        protected static function AnotherOne()
        {
            echo "Non Static Method Another is calling \n";
        }
        
        private static function AgainOne()
        {
            echo "Non Static Private Method Again is calling \n";
        }
        
        
        public static function bypass()
        {
            return self::AgainOne();
        }
        
        public function getPText()
        {
            return $this->ptext;
        }
        
        
        
    }
    ?>
    

    现在测试这个类

    <?php
    
    //Non Static Call By Creating an $app instance of Foo Class..
    $app = new Foo();
     echo $app->WELCOME;        // Undefined property: Foo::$WELCOME
     echo $app->text;           // This is A Text Non Static Foo Class Properties
     echo $app->texter;         // Accessing static property Foo::$texter as non static
     echo $app->Bar();          // Static Method Bar is calling
     echo $app->Baz();          // Non Static Method Baz is calling 
     echo $app->Another();      // Uncaught Error: Call to protected method Foo::Another() from global scope
     echo $app->Again();        // Uncaught Error: Call to private method Foo::Again() from global scope
     echo $app->AnotherOne();   // Uncaught Error: Call to protected method Foo::AnotherOne() from global scope
     echo $app->AgainOne();     // Uncaught Error: Call to private method Foo::AgainOne() from global scope
     echo $app->bypass();       // Non Static Private Method Again is calling 
     echo $app->ptext;          // Uncaught Error: Cannot access private property Foo::$ptext
     echo $app->getPText();     // This is a private string Non Static properties of Class Foo 
    
    //Static Call
     echo Foo::WELCOME;         // This is WELCOME Non Static Constant For Foo Class
     echo Foo::text;            // Uncaught Error: Undefined constant Foo::text
     echo Foo::texter;          // Uncaught Error: Undefined constant Foo::texter
     echo Foo::Bar();           // Static Method Bar is calling
     echo Foo::Baz();           // Uncaught Error: Non-static method Foo::Baz() cannot be called statically
     echo Foo::Another();       // Uncaught Error: Call to protected method Foo::Another() from global scope
     echo Foo::Again();         // Uncaught Error: Call to private method Foo::Again() from global scope 
     echo Foo::AnotherOne();    // Uncaught Error: Call to protected method Foo::AnotherOne() from global scope
     echo Foo::AgainOne();      // Uncaught Error: Call to private method Foo::AgainOne() from global scope
     echo Foo::bypass();        // Non Static Private Method Again is calling 
     
     ?>
    
    

    查看实际操作here

    【讨论】:

    • 请在您的答案中添加一些解释,以便其他人可以从中学习。代码有什么作用?它如何回答给定的问题?
    • 任何静态类方法都可以非静态调用..但非静态方法不能静态调用.. Like Posts::create();也可以通过 $post = new Posts(); 调用$post->create();因此可以使用非 staic 操作 staic 方法,这可能是一些 php hack 或 Php 功能。也用于声明,class xyz { public static function abc(){} // Static Method, public function abc(){} // non static method }
    • 请通过编辑将所有解释 添加到您的答案
    • 谢谢,Nicco Haase,我更新了我的答案...
    【解决方案6】:

    很抱歉碰到一个旧线程,但我想扩展 @lonesomeday 的答案。 (感谢@lonesomeday 提供初始代码示例。)

    我也在尝试这个,但不想调用他在原始帖子中调用的方法。相反,我有以下,似乎可以工作:

        class Emailer {
    
        private $recipient;
    
        public function to( $recipient )
        {
            $this->recipient = $recipient;
            return $this;
        }
    
        public function sendNonStatic()
        {
            self::mailer( $this->recipient );
        }
    
        public static function sendStatic( $recipient )
        {
            self::mailer( $recipient );
        }
    
        public function __call( $name, $arguments )
        {
            if ( $name === 'send' ) {
                call_user_func( array( $this, 'sendNonStatic' ) );
            }
        }
    
        public static function mailer( $recipient )
        {
            // send()
            echo $recipient . '<br>';
        }
    
        public static function __callStatic( $name, $arguments )
        {
            if ( $name === 'send' ) {
                call_user_func( array( 'Emailer', 'sendStatic' ), $arguments[0] );
            }
        }
    }
    
    Emailer::send( 'foo@foo.foo' );
    
    $Emailer = new Emailer;
    $Emailer->to( 'bar@bar.bar' );
    $Emailer->send();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多