php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #49376 ReflectionClass::newInstanceArgs cannot instantiate a constructorless class
Submitted: 2009-08-26 16:12 UTC Modified: 2009-09-14 18:22 UTC
From: sebcsaba at freemail dot hu Assigned:
Status: Not a bug Package: Reflection related
PHP Version: 5.3.0 OS: WinXP
Private report: No CVE-ID: None
 [2009-08-26 16:12 UTC] sebcsaba at freemail dot hu
Description:
------------
I've got a class without a constructor, and I want to instantiate it by ReflectionClass::newInstanceArgs with an empty array as arguments.
This causes:
ReflectionException: 'Class A does not have a constructor, so you cannot pass any constructor arguments'.

If I define an empty default constructor, this works well.

Reproduce code:
---------------
class A {}
$rc = new ReflectionClass('A');
$a = $rc->newInstanceArgs(array());


Expected result:
----------------
Create a new instance of class A, using default constructor behaviour.


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-08-28 23:14 UTC] felipe@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

Do not pass any param to method. Just use $rc->newInstanceArgs();
 [2009-09-14 18:22 UTC] sebcsaba at freemail dot hu
Thank you for taking the time to write to me, but if this is not a bug then this is a bad design of the method.

I've double-checked the documentation available at http://php.net/manual/en/reflectionclass.newinstanceargs.php which said 'This function is currently not documented; only its argument list is available.' and said nothing about the numbers of the element in the given array.

If you want to make a factory function with vararg, then you don't want to case about the number of the parameters.

I think this should work:

function factory($className /* and other params here... */ ) {
  $rc = new ReflectionClass($className);
  $params = func_get_args();
  array_shift($params);
  return $rc->newInstanceArgs($param);
}

The new $className(...) construction doesn't work here.

What is the difference between
  class A {}
and
  class A { function __construct(){} }
from the view of the construction? Both can be constructed by a zero-arg constructor call, new A(). If I've an array containing zero elements, why should not the $rc->newInstanceArgs($array) works in the first case, even it does in the second?
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Oct 16 08:01:27 2024 UTC