php expression is not allowed as field default value
When the declaration of a PHP class variable we cannot perform any expressions, e.g.:
only we can just provide constants e.g.:
Can anybody knows why its like that?
5 Answers 5
That is because expression is not allowed as field default value. Make use of constructors to initialize the variables instead.
I suggest you do like this..
You cannot use statement or function, just a scalar value. This is because class variables are initiated in compile time (before runtime). Class constructor should be used to initiate property with statement/function.
You can only perform expressions on Properties in constructor or other member functions of the class.
Note that, you can initialize value to property outside of constructor and member functions too. But It’s impossible to make the expression. The best practice is to initialize and perform expressions in Constructor and member functions of the class.
When declaring a class variable in PHP OOP, they are called class member variables or class properties. The reason why we cannot assign values or perform any expression or calculation is that You’re declaring the structure of the class here, which is not the same as a variable assignment in procedural code. The OOP PHP class structure is parsed by php Parser and Compiled, while doing this operation the Compiler does not execute any procedural code. It can only handle constant values.
As you already now the following will not work and one gets syntax error.
But you can achieve the same thing by using constant in class like this.
If you need to do operations you do this by using methods or even class constructor if needed.
Well if it has something to do with initializing a new database name via «file.txt» which you refer through a certain path, what I did to resolve such problem is this:
Not the answer you’re looking for? Browse other questions tagged php oop or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Best workaround to create a PHP class constant from an expression?
I’d like to be able to do something like this:
But I can’t create a class constant from an expression like that:
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
So my question is: What’s the best workaround for this limitation of PHP? I’m aware of the following workarounds, but are there any others which are better?
1. Create a property
2. Use define()
This is better, since the value is truly constant, but the drawback is that RAD_TO_CIRCUM has been globally defined.
A digression
I don’t understand how this can work. (Edit: I’ve tested it, and it does work.) According to the Handbook of PHP Syntax:
The const modifier creates a compile-time constant and so the compiler will replace all usage of the constant with its value. In contrast, define creates a run-time constant which is not set until run-time. This is the reason why define constants may be assigned with expressional values, whereas const requires constant values which are known at compile-time.
In this bug report from 3 years ago, a member of the PHP team wrote:
For the class constant we need a constant value at compile time and can’t evaluate expressions. define() is a regular function, evaluated at run time and can therefore contain any value of any form.
3. Create a method
This is my favourite workaround that I’m aware of. The value is constant, and it doesn’t affect the global space.
Is there another workaround which is even better?
How to set default value for form field in Symfony2?
Is there an easy way to set a default value for text form field?
22 Answers 22
you can set the default value with empty_data
Can be use during the creation easily with :
I’ve contemplated this a few times in the past so thought I’d jot down the different ideas I’ve had / used. Something might be of use, but none are «perfect» Symfony2 solutions.
If statements within get’s I wouldn’t, but you could.
Factory / instance. Call a static function / secondary class which provides you a default Entity pre-populated with data. E.g.
Not really ideal given you’ll have to maintain this function if you add extra fields, but it does mean you’re separating the data setters / default and that which is generated from the db. Similarly you can have multiple getFactories should you want different defaulted data.
Set Data before build form In the constructors / service, you know if you have a new entity or if it was populated from the db. It’s plausible therefore to call set data on the different fields when you grab a new entity. E.g.
Form Events When you create the form you set default data when creating the fields. You override this use PreSetData event listener. The problem with this is that you’re duplicating the form workload / duplicating code and making it harder to maintain / understand.
Extended forms Similar to Form events, but you call the different type depending on if it’s a db / new entity. By this I mean you have FooType which defines your edit form, BarType extends FooType this and sets all the data to the fields. In your controller you then simply choose which form type to instigate. This sucks if you have a custom theme though and like events, creates too much maintenance for my liking.
Twig You can create your own theme and default the data using the value option too when you do it on a per-field basis. There is nothing stopping you wrapping this into a form theme either should you wish to keep your templates clean and the form reusable. e.g.
JS It’d be trivial to populate the form with a JS function if the fields are empty. You could do something with placeholders for example. This is a bad, bad idea though.
Forms as a service For one of the big form based projects I did, I created a service which generated all the forms, did all the processing etc. This was because the forms were to be used across multiple controllers in multiple environments and whilst the forms were generated / handled in the same way, they were displayed / interacted with differently (e.g. error handling, redirections etc). The beauty of this approach was that you can default data, do everything you need, handle errors generically etc and it’s all encapsulated in one place.
To that end, I’ve approached the problem differently each time. For example, a signup form «newsletter» option is easily (and logically) set in the constructor just before creating the form. When I was building forms collections which were linked together (e.g. which radio buttons in different form types linked together) then I’ve used Event Listeners. When I’ve built a more complicated entity (e.g. one which required children or lots of defaulted data) I’ve used a function (e.g. ‘getFactory’) to create it element as I need it.
I don’t think there is one «right» approach as every time I’ve had this requirement it’s been slightly different.
Good luck! I hope I’ve given you some food for thought at any rate and didn’t ramble too much 😉
Php expression is not allowed as field default value
I have two models where i wish to set a autogenerated value when i create a new. \n
E.g. i have a slug field in one and a uuid field in the other one. \n
I tried to look at the default attributes, but they don’t accept expressions like \n
append your model with: \n
Thank you for your idea on this. Much appriciated. 🙂 \n
I was looking mutators, but the idea was to set the uuid automatically whenever i create a new object, or call the save() method.\nWith the get mutator, the value is not persisted in the database. \n
So my thought was to put it in the boot() override, create an event listener on the saving event or create a trait.\nBut i can’t really figure out the best\/easier\/fastest way here. \n
I have seen a trait to replace the auto increment with uuid, but in this case the uuid is a additional field and not an replacement. \n»,»bodyInMarkdown»:»Hi,\r\n\r\nThank you for your idea on this. Much appriciated. :)\r\n\r\nI was looking mutators, but the idea was to set the uuid automatically whenever i create a new object, or call the save() method.\r\nWith the get mutator, the value is not persisted in the database.\r\n\r\nSo my thought was to put it in the boot() override, create an event listener on the saving event or create a trait.\r\nBut i can’t really figure out the best\/easier\/fastest way here.\r\n\r\nI have seen a trait to replace the auto increment with uuid, but in this case the uuid is a additional field and not an replacement.»,»replies»:[],»user»:<"id":13640,"username":"cboxdk","avatar":"\/\/unavatar.now.sh\/github\/SylvesterNielsen","experience":<"award_count":"3","level":6,"points":"26,635","pointsUntilNextLevel":"3,365">,»achievements»:[],»reported»:null,»profile»:<"github":"SylvesterNielsen","twitter":"","full_name":null,"website":"","bio":null>,»dateSegments»:<"created_diff":"6 years ago">>,»likes»:[],»created_at»:»2015-12-28T14:53:34.000000Z»,»links»:<"delete":"\/discuss\/replies\/126092","like":"\/discuss\/replies\/126092\/likes","best_answer":"\/discuss\/conversations\/26690\/best">,»best_answer»:false,»dateSegments»:<"createdDiff":"5 years ago">>,<"id":126093,"conversation_id":26690,"body":"
May be something like this \n
For this I usually do it in either the save method, or in a creating \/ saving event. \n
I ended up with this. It works at least.. Thank you everyone. 🙂 \n
Сменил хост получил, Field ‘поле’ doesn’t have a default value?
Если у вас возникает ошибка mysql:
«Field xxx doesn’t have a default value»
это означает, что при вставке или обновлении данных у поля нет значения по умолчанию. Для решения проблемы нужно:
найти данный запрос и исправить его, добавить необходимое поле;
в свойствах таблицы указать значение по умолчанию;
Еще одним способом решения является выключение режима mysql: «Strict Mode», т.е. мы выключаем режим строгого соответствия стандарту MySql.
Выключить его можно в конфиге my.ini:
прописав вместо:
Или выполнив следующий запрос:
Проблема в вашем коде. Наконец-то mysql начал об этом говорить. Нельзя писать в таблицу, не указывая явным образом значения для всех полей, не имеющих default значения.
Вероятно, вы смигрировались на mysql 5.7. Там как раз sql_mode дефолтный наконец-то изменили. А может просто более адекватно sql_mode выставлен админом.
dev.mysql.com/doc/refman/5.7/en/sql-mode.html
На сколько помню, за поведение ошибочного insert’а без указания non-default полей отвечают STRICT_ALL_TABLES, STRICT_TRANS_TABLES.