PHP에서 객체를 인스턴스화하고 같은 줄에서 메소드를 호출 할 수 있습니까?
내가하고 싶은 것은 다음과 같습니다.
$method_result = new Obj()->method();
하지 말고 :
$obj = new Obj();
$method_result = $obj->method();
특정 상황에서는 결과가 실제로 중요하지 않습니다. 그러나 이것을 할 수있는 방법이 있습니까?
요청한 기능은 PHP 5.4에서 사용할 수 있습니다. 다음은 PHP 5.4의 새로운 기능 목록입니다.
http://php.net/manual/en/migration54.new-features.php
그리고 새로운 기능 목록에서 관련 부분 :
인스턴스화에 대한 클래스 멤버 액세스가 추가되었습니다 ( 예 : (new Foo)-> bar ()).
당신이 원하는 것을 할 수는 없습니다. 그러나 PHP에서 클래스와 동일한 이름을 가진 함수를 가질 수 있다는 사실을 사용하여 "속임수"를 사용할 수 있습니다. 그 이름은 충돌하지 않습니다.
따라서 다음과 같이 클래스를 선언하면 :
class Test {
public function __construct($param) {
$this->_var = $param;
}
public function myMethod() {
return $this->_var * 2;
}
protected $_var;
}
그런 다음 해당 클래스의 인스턴스를 반환하고 클래스와 정확히 동일한 이름을 가진 함수를 선언 할 수 있습니다.
function Test($param) {
return new Test($param);
}
이제는 요청 한대로 하나의 라이너를 사용할 수 있습니다. 단지 함수를 호출하는 것만으로 new :
$a = Test(10)->myMethod();
var_dump($a);
그리고 그것은 작동합니다 : 여기, 나는 얻고 있습니다 :
int 20
출력으로.
그리고 더 나은 것은 함수에 phpdoc을 넣을 수 있다는 것입니다.
/**
* @return Test
*/
function Test($param) {
return new Test($param);
}
이런 식으로 IDE에 힌트를 얻을 수 있습니다. 적어도 Eclipse PDT 2.x에서는 힌트가 있습니다. screeshot을 참조하십시오 :
편집 2010-11-30 : 며칠 전에 새로운 RFC가 제출되어 향후 PHP 버전 중 하나에이 기능을 추가 할 것을 제안합니다.
참조 : 의견 요청 : 인스턴스 및 메소드 호출 / 속성 액세스
따라서 PHP 5.4 또는 다른 향후 버전에서 이와 같은 작업을 수행 할 수 있습니다.
(new foo())->bar()
(new $foo())->bar
(new $bar->y)->x
(new foo)[0]
어때요?
$obj = new Obj(); $method_result = $obj->method(); // ?
:피
You can do it more universally by defining an identity function:
function identity($x) {
return $x;
}
identity(new Obj)->method();
That way you don't need to define a function for each class.
No, this is not possible.
You need to assign the instance to a variable before you can call any of it's methods.
If you really wan't to do this you could use a factory as ropstah suggests:
class ObjFactory{
public static function newObj(){
return new Obj();
}
}
ObjFactory::newObj()->method();
You could use a static factory method to produce the object:
ObjectFactory::NewObj()->method();
I, too, was looking for a one-liner to accomplish this as part of a single expression for converting dates from one format to another. I like doing this in a single line of code because it is a single logical operation. So, this is a little cryptic, but it lets you instantiate and use a date object within a single line:
$newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : '');
Another way to one-line the conversion of date strings from one format to another is to use a helper function to manage the OO parts of the code:
function convertDate($oldDateString,$newDateFormatString) {
$d = new DateTime($oldDateString);
return $d->format($newDateFormatString);
}
$myNewDate = convertDate($myOldDate,'F d, Y');
I think the object oriented approach is cool and necessary, but it can sometimes be tedious, requiring too many steps to accomplish simple operations.
I see this is quite old as questions go but here is something I think should be mentioned:
The special class method called "__call()" can be used to create new items inside of a class. You use it like this:
<?php
class test
{
function __call($func,$args)
{
echo "I am here - $func\n";
}
}
$a = new test();
$a->new( "My new class" );
?>
Output should be:
I am here - new
Thus, you can fool PHP into making a "new" command inside of your top level class (or any class really) and put your include command in to the __call() function to include the class that you have asked for. Of course, you would probably want to test $func to make sure it is a "new" command that was sent to the __call() command and (of course) you could have other commands also because of how __call() works.
'Programming' 카테고리의 다른 글
안드로이드에서 열거 형 작업 (0) | 2020.07.20 |
---|---|
IntelliJ에서 치명적인 오류가 발생 함 : classpath 또는 bootclasspath에서 java.lang 패키지를 찾을 수 없음 (0) | 2020.07.19 |
파이썬에서 다중 선형 회귀 (0) | 2020.07.19 |
WPF ListBox에서 가로 스크롤을 비활성화하려면 어떻게해야합니까? (0) | 2020.07.19 |
getMinimum ()이 O (1)이되도록 스택을 설계하십시오. (0) | 2020.07.19 |