Simple question, is it possible to dynamically add traits to a php class in runtime without using eval?
As Glavic said, you can't without using eval() or reflection hacks (and I'm not even sure about that).
But it's very unlikely you really need to.
You can achieve a lot with dynamic class composition (composing a class with some functionality you want into another class). That's simply a matter of putting a reference to the class with the desired functionality into a variable in the hosting class.
class SomeClassWithNeededFunctionality {}
class SomeClassThatNeedsTheFunctionalityOfTheOtherClass {
private $serviceClass = NULL;
public function __construct (SomeClassWithNeededFunctionality $serviceClass) {
$this -> serviceClass = $serviceClass;
}
}
No.
p.s. you can have them in standalone files, and use include() ?
I'm looking at some one else's code that I do not understand. This is example of class:
class ImageService
{
public function __construct(
private ImageTransformer $imageTransformer,
private PostService $postService
) {
}
// other methods here
}
IDE is showing errors under _construct due to "private" inside params.
I know that in PHP 8 there are union types, but I cannot find any info about using "private" or "public" not inside class but inside constructor, and what this supposed to do. I thought that this is typo, and it supposed to be inside class, but multiple classes are created like this. Is this a valid code or someone does not know what is he doing?
This is new in PHP 8.0.0 and is called Constructor Promotion.
As of PHP 8.0.0, constructor parameters may also be promoted to correspond to an object property. It is very common for constructor parameters to be assigned to a property in the constructor but otherwise not operated upon. Constructor promotion provides a short-hand for that use case.
If you execute that code you will see. You should check to see if your IDE has been updated to support PHP 8.0.0.
The history of PHP says that the older versions of PHP use the class name as a method for a constructor for the same class.
The PHP 5.3.3 documentation says that:
Methods with the same name as the last element of a
namespaced class name will no longer be treated as constructor. This
change doesn't affect non-namespaced classes.
Example:
namespace A;
class classOne{
public function methodOne(){}
public function methodTwo(){}
public function classOne(){} //Constructor
}
class classTwo{
public function methodOne(){}
public function methodTwo(){}
public function classTwo(){} //Constructor
}
So according to this documentation, classOne() and classTwo() are not considered as constructors? What is the reasoning behind this? Can anyone tell me?
Reference Link
Regarding why this rule applies for namespaced classes vs. non-namespaced, PHP 5.3 introduced namespaces. If you were upgrading from an older PHP version, you would have non-namespaced classes to look after, potentially using the old style way of creating constructors.
They want to enforce that you are developing within modern PHP principles and that you are also using the new conventions. PHP at this point is committed to removing old-style constructors completely, which we have seen as they are deprecated in PHP 7 and will be removed in a future version.
Finally, the reasoning behind dropping this convention altogether is that it is more error-prone. Using the DRY principles, if one was to change a class name while refactoring, forgetting to change the name of the constructor, it could have subtle and not-so-subtle repercussions.
If you are extending a class and want to call its constructor, it is also more error-prone if their parent class's name changes. For further reading:
https://stackoverflow.com/a/29794401/823549
and
https://stackoverflow.com/a/217876/823549.
I haven't got a better clarity after a long search about, using keyword public in a __constructor function in a PHP class.
People saying __constructor itself is public by default. So I don't have to use mention as public.
Will there be no change if I mention or don't as public in public function __constructor in PHP?
what is the best practice of declaring a __constructor in PHP? with or without the keyword public?
what are the disadvantages or issues that I will face if I don't mention the keyword public in-front of a public function __constructor?
PSR-2 ยง4.3 reads:
Visibility MUST be declared on all methods.
__constructor is one of "all methods", so the rule applies.
__constructor is a method. Visibility of methods is described in PHP Doc as:
Class methods may be defined as public, private, or protected. Methods
declared without any explicit visibility keyword are defined as
public.
So there is no need to write 'public' visibility for public methods.
But still I prefer to write explicitly visibilities (even 'public') for methods - code is more obvious for everyone.
Default is public. It's a good practice to always include it, however PHP4 supported classes without access modifiers, so it's common to see no usage of them in legacy code.
Since nobody mentions it.
function __constructor ()
Is a function that will run when the class is made. Check https://stackoverflow.com/a/455929/7423021 for bigger details
Is there any advantage to using __construct() instead of the class's name for a constructor in PHP?
Example (__construct):
class Foo {
function __construct(){
//do stuff
}
}
Example (named):
class Foo {
function Foo(){
//do stuff
}
}
Having the __construct method (first example) is possible since PHP 5.
Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.
I agree with gizmo, the advantage is so you don't have to rename it if you rename your class. DRY.
Similarly, if you have a child class you can call
parent::__construct()
to call the parent constructor. If further down the track you change the class the child class inherits from, you don't have to change the construct call to the parent.
It seems like a small thing, but missing changing the constructor call name to your parents classes could create subtle (and not so subtle) bugs.
For example, if you inserted a class into your heirachy, but forgot to change the constructor calls, you could started calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice.
Also note that
As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
Source: http://php.net/manual/en/language.oop5.decon.php
__construct was introduced in PHP5. It is the way you are supposed to do it now. I am not aware of any advantages per se, though.
From the PHP manual:
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics
If you're on PHP5 I would recommend using __construct to avoid making PHP look elsewhere.
The main advantage I see for __construct, is that you don't have to rename your constructor if you change your class name.
Today, the accepted answer is obsolete.
Renaming classes is bad practice: you have to remember what and where to rename everytime you upgrade to newer version. Sometimes (like using Reflection or complex dependence structure) it can be impossible without radical refactoring. And this is accidental complexity you want to avoid. That's why namespaces were introduced into PHP. Java, C++ or C# don't use __construct, they use named constructor and there's no issue with them.
As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
Example
namespace Foo;
class Test {
var $a = 3;
function Test($a) {
$this->a = $a;
}
function getA() {
return $this->a;
}
}
$test = new Test(4);
echo $test->getA(); // 3, Test is not a constructor, just ordinary function
Note that named constructors are not deprecated (PHP 5.5 today). However, you can't predict that your class won't be used in namespace, therefore __construct should be preffered.
Clarification about the bad practice mentioned above (for Dennis)
Somewhere in your code you could use ReflectionClass::getName(); when you rename the class, you need to remember where you used Reflection and check if the getName() result is still consistent in your app. The more you need to remember something specific, the more likely something is forgotten which results in bugs in the app.
The parents can't have control about all the classes in the world which depends on them. If allow_url_include is enabled, some other web might be using the class from your server, which may crash if you rename some class. It is even worse in compiled languages mentioned above: the library can be copied and bundled in other code.
There is no reason why to rename class:
if the class name conflicts, use namespaces
if the class responsibility shifts, derive some other class instead
In PHP classes in namespace, the method with the same name should be avoided anyway: intuitively it should produce an object created the class; if it does something else, why to give it the same name? It should be a constructor and nothing else. The main issue is that the behavior of such a method depends on namespace usage.
There is no issue with __construct constructors in PHP. But it wasn't the smartest idea to alter the named constructors.
The best advantage of using __contruct() instead of ClassName() is when extending classes. It is much easier to call parent::__construct() instead of parent::ClassName(), as it is reusable among classes and the parent can be changed easily.
In your example Foo::Foo is sometimes called a PHP 4 or old-style constructor because it comes from the days of PHP 4:
class Foo {
// PHP 4 constructor
function Foo(){
//do stuff
}
}
PHP 4 constructors will be deprecated but not removed in PHP 7. They will be no longer be considered as constructors in any situation in PHP 8. Future compatibility is definitely a big reason to not use this feature.
Well it has been a few years since this question was asked, but I think I have to answer this one still, because things has changed and for readers in the future I want to keep the information up to date!
So in php-7 they will remove the option to create the constructor as a function with the same name as the class. If you still do it you will get a E_DEPRECATED.
You can read more about this proposal (the proposal is accepted) here:
https://wiki.php.net/rfc/remove_php4_constructors
And a quote from there:
PHP 7 will emit E_DEPRECATED whenever a PHP 4 constructor is defined. When the method name matches the class name, the class is not in a namespace, and a PHP 5 constructor (__construct) is not present then an E_DEPRECATED will be emitted. PHP 8 will stop emitting E_DEPRECATED and the methods will not be recognized as constructors.
Also you won't get a E_STRICT in php-7 if you define a method with the same name as the class AND a __construct().
You can see this also here:
PHP 7 will also stop emitting E_STRICT when a method with the same name as the class is present as well as __construct.
So I would recommend you to use __construct(), since you will have less issues with this in the future.
In PHP 5 the advantage would be that performance would be better. It will look for a constructor by the name of __construct first and if it doesn't find that, it will look for constructors by the name of className. So if it finds a constructor by the name __construct it does not need to search for a constructor by the name className.
Forward compatibility. There's always a chance that legacy code that's left in the language for backwards compatibility's sake will be removed in a future version.
If there is methods __construct and SameAsClassName method then __construct will be executed, SameAsClassName method will be skipped.
I think that the main reason is that is the language convention.
You don't need to force a language to act like someone else.
I mean, in Objective-C you prefix the constructors with -init, for example. You can make your own constructor using your class name but why? Are ther some reason to use this schema instead of the language convention?