2010-06-23 103 views
4

我看了一下,试过但我找不到答案。调用没有对象实例化的类方法(带构造函数)在php

在PHP中,是否有可能在不实例化对象的情况下调用类的成员函数(当该类需要构造函数来接收参数时)?

A码的例子(其给出错误):

<?php 

class Test { 
    private $end=""; 

    function __construct($value) { 
     $this->end=$value; 
    } 

    public function alert($value) { 
     echo $value." ".$this->end; 
    } 
} 

//this works: 
$example=new Test("world"); 
$example->alert("hello"); 

//this does not work: 
echo Test("world")::alert("hello"); 

?> 
+0

我想回声测试:: __结构( “世界”)::警报( “你好”);可能工作,但它不,叹息 – mykchan 2010-06-23 04:07:36

+0

使alert()静态函数将完成这项工作。 – 2014-02-25 10:10:42

回答

0

你不能没有一个实例调用一个实例级方法。你的语法:

echo Test("world")::alert("hello"); 

不使一个很大的意义。要么您正在创建内联实例并立即将其丢弃,要么方法没有隐式的this实例。

假设:

class Test { 
    public function __construct($message) { 
    $this->message = $message; 
    } 

    public function foo($message) { 
    echo "$this->message $message"; 
    } 
} 

你可以这样做:

$t = new Test("Hello"); 
$t->foo("world"); 

但PHP语法不允许:

new Test("Hello")->foo("world"); 

,否则便等同。在PHP中有一些这样的例子(例如,在函数返回时使用数组索引)。就是那样子。

+1

我正在创建一个内联实例并立即丢弃它。我不明白为什么我需要为这个过程分配一个变量......这只是PHP/OOP的方式吗? – mykchan 2010-06-23 04:16:00

18

不幸的是PHP没有支持,要做到这一点,但你是一个创造性的和看的人:d

您可以使用“工厂”,示例:

<?php 

class Foo 
{ 
    private $__aaa = null; 

    public function __construct($aaa) 
    { 
     $this->__aaa = $aaa; 
    } 

    public static function factory($aaa) 
    { 
     return new Foo($aaa); 
    } 

    public function doX() 
    { 
     return $this->__aaa * 2; 
    } 
} 

Foo::factory(10)->doX(); // outputs 20 
1

我也一样,正在寻找一个单线程来完成这一点,作为将日期从一种格式转换为另一种格式的单一表达式的一部分。我喜欢在单行代码中执行此操作,因为它是单个逻辑操作。所以,这是一个有点神秘,但它可以让你实例化和单行中使用的日期对象:

$newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : ''); 

的另一种方式,以一个行日期字符串从一种格式转换为另一种是使用辅助功能,可管理代码的OO部分:

function convertDate($oldDateString,$newDateFormatString) { 
    $d = new DateTime($oldDateString); 
    return $d->format($newDateFormatString); 
} 

$myNewDate = convertDate($myOldDate,'F d, Y'); 

我认为面向对象的方法是凉的和必要的,但有时也可能是乏味的,需要太多的步骤来完成简单的操作。

4

只是这样做(在PHP> = 5.4):

$t = (new Test("Hello"))->foo("world"); 
相关问题