you have not defined the type of $insert. Since you are using strict types and the $insert parameter indicates whether the model is being inserted or updated, it is a boolean value (as per Yii2's beforeSave method):
php
public function beforeSave(bool $insert): bool
So yes, you can and should define the type of $insert as bool:
php
public function beforeSave(bool $insert): bool
{
if (!parent::beforeSave($insert)) {
return false;
}
// your code here
return true;
}
Summary:
Type hint $insert as bool because it is a boolean flag.
Make sure your declare(strict_types=1); is set at the top of your PHP file to enforce strict typing.
This matches the parameter type definition used by Yii2 (bool $insert) in beforeSave().
User
why does type strict breaks some fnctions
Assistant
Great question! When you enable strict types in PHP (declare(strict_types=1);), the language enforces exact types on function arguments and return values based on the type declarations. This strict enforcement can cause some functions to break or throw type errors if they receive arguments of a different type than declared, or if they return values that don't match their declared return type.
Why does strict type checking break some functions?
Type Mismatch on Parameters
Without strict types (the default in PHP), if a function expects an int and you pass a string "123", PHP will attempt to coerce (convert) that string to an integer. With strict types enabled, PHP does not convert the types implicitly — so passing "123" to a function expecting int will cause a TypeError.
This can break existing code or code from libraries that rely on type coercion.
Type Mismatch on Return Values
Similarly, if a function declares a return type of int but returns a string "123", PHP throws a TypeError with strict types enabled. Without strict types, PHP allows this with coercion.
Legacy Code and Third-Party Libraries
Many older PHP codebases or libraries were written without strict typing in mind and may pass loosely typed values. Enabling strict types may cause them to break until they're refactored or updated.
Interfaces and Overriding Methods
Inherited or overwritten methods in classes must match the parent method’s signature exactly, including parameter and return types. Mismatches here, combined with strict types, also cause errors.
Example
php
declare(strict_types=1);
function add(int $a, int $b): int
{
return $a + $b;
}
echo add(1, 2); // works fine
echo add("1", 2); // TypeError: Argument 1 passed to add() must be of the type int, string given
Without declare(strict_types=1);, calling add("1", 2) would work because "1" is cast to the integer 1 automatically.
How to Avoid Problems?
Enable strict types gradually: Don't enable it everywhere at once; add it module-by-module or file-by-file.
User
so if the oringal does not inforce? i also get erros i fine
Assistant
Yes, that's right — even if the original code or library you use does not enforce strict types (i.e., it does not have declare(strict_types=1);), you can still get errors under certain circumstances.
Here's why:
1. PHP Type Hinting and Compatibility
Even without strict types enabled, PHP enforces some basic type checks for type-hinted parameters and return types, but it attempts to coerce types loosely. However:
If you pass a completely incompatible type (e.g., an array instead of an int or object), PHP will throw a TypeError even without strict types.
PHP 7+ introduced scalar type hints and return type declarations, so violating these causes errors, sometimes even in coercive (non-strict) mode.
2. Optional Strictness
Non-strict mode allows coercion on scalar types (e.g., strings "1" to ints 1), but object types and class inheritance must match exactly.
So if you pass a wrong class or null when not allowed, PHP will throw a fatal error or TypeError regardless of strict/non-strict mode.
3. Return Types
Return type declarations are always enforced strictly — PHP won't automatically coerce a wrong return type, even in non-strict mode. This means a function returning the wrong type triggers a fatal error immediately.
What this means practically for you:
Without strict types:
PHP attempts to convert scalar input types.
You might not get errors for loosely passed values like string "1" to int.
But non-scalar type mismatches (wrong class, array instead of int) and invalid return values do cause errors.
With strict types (declare(strict_types=1);):
PHP requires exact matches on scalar parameter types — no coercion allowed.
Same strict enforcement on return types.
Non-scalar rules remain the same.
More errors may surface because of stricter parameter checks.
Example without strict_types:
php
User
i noticed that with:
code
/**
* Finds an identity by the given ID.
* @see yii\web\IdentityInterface
* @param string|int $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
*
* Null should be returned if such an identity cannot be found
* or the identity is not in an active state (disabled, deleted, etc.)
*
* Note: Do not define $id in findIdentity() function.
*/
public static function findIdentity($id): IdentityInterface|null
{
return static::find()->where(['id' => $id])->active()->one();
//return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
since im assuming yii2 does not define $id in its code.. i tried int|string since the doc says this but it throws error
Assistant
Your observation is correct, and this is a common subtlety when working with PHP and Yii2’s interfaces combined with strict typing.
What's going on?
The method findIdentity() is defined by the IdentityInterface in Yii2 as:
php
public static function findIdentity($id);
No type hint on $id (i.e. untyped, accepts anything).
No return type hintin the interface (in older Yii2 versions).
Documentation (@param) says $id can be string|int.
PHP's interface requires your implementation to be compatible with this signature.
Why does adding int|string $id cause an error?
Because your implementation's parameter type hint must be compatible with the interface:
The interface specifies no type hint on $id, meaning it can accept anything.
If you add a more specific type hint like int|string in your implementation, PHP considers that incompatible with the interface and throws a fatal error: "Declaration of Class::findIdentity(int|string id) must be compatible with interface Interface::findIdentity(\id)"
How to deal with this?
1. Don’t add a type hint on $id in your method signature
Use:
php
public static function findIdentity($id): IdentityInterface|null
{
return static::find()->where(['id' => $id])->active()->one();
}
This is compatible with the parent interface. You can still rely on the docblock annotation to indicate your expected types:
php
/**
* @param string|int $id
* @return IdentityInterface|null
*/
public static function findIdentity($id): IdentityInterface|null
{
...
}
2.
User
can you help me make a comment that is short, sweet detailed enough that i can add to functions like this one. so for future referenvce i dont define it and cause errors
Assistant
Certainly! Here's a concise, clear comment you can add to such functions to remind yourself (and others) not to add strict parameter type hints when overriding interface methods that don't declare them—especially when the docs suggest broad accepted types like int|string:
php
/**
* Do NOT add parameter type hints here, even if the doc says string|int.
* This method overrides an interface without type hints on parameters,
* so adding types will cause PHP compatibility errors.
* Use only docblock types to indicate expected input types.
*/
Example usage:
php
/**
* Do NOT add parameter type hints here, even if the doc says string|int.
* This method overrides an interface without type hints on parameters,
* so adding types will cause PHP compatibility errors.
* Use only docblock types to indicate expected input types.
*
* @param string|int $id
* @return IdentityInterface|null
*/
public static function findIdentity($id): IdentityInterface|null
{
return static::find()->where(['id' => $id])->active()->one();
}
This keeps it:
Short and to the point
Explains why no param types (PHP override rules)
Reminds you to document types in the docblock only
Avoids confusion for future you and other devs
If you want something even shorter or more formal, just ask!
User
Do NOT add parameter type hints here, even if the doc says string|int.
This method overrides an interface without type hints on parameters,
so adding types will cause PHP compatibility errors.
Use only docblock types to indicate expected input types.
shorter
Assistant
Sure! Here's a shorter version that still covers the essentials:
php
/**
* Do NOT add parameter types here—even if doc says string|int—
* to avoid PHP method signature incompatibility errors.
* Use docblocks to specify expected types only.
*/
User
will
public function beforeSave($insert): bool
{
adding bool to $insert cuase the same issie?
Assistant
Good question!
Does adding bool type hint to $insert in beforeSave($insert) cause the same issue?
Answer: Usually NO, because:
The beforeSave() method is defined in Yii2’s BaseActiveRecord class with the parameter type declared as bool $insert (in Yii2 2.0.14+).
Your method is overriding a parent method that already has bool $insert.
So adding bool $insert in your override matches the parent's signature exactly.
This is allowed by PHP's method signature rules (parameter types must be compatible; matching is ok).
To verify, let's look at Yii2's signature for beforeSave
php
public function beforeSave(bool $insert): bool
bool $insert is declared in the parent method
You can (and should) type hint bool $insert in your override to be consistent and take advantage of strict typing.
Summary:
Scenario
Can you add type hint?
Overriding interface method with no param hint
No, causes incompatibility
Overriding parent method with type hint
Yes, must match parent type
In your case:
php
public function beforeSave(bool $insert): bool
is perfectly correct and won’t cause PHP errors. In fact, it's recommended for strict typing.
TL;DR
beforeSave(bool $insert) is fine and matches Yii2 method declaration.
Adding bool here does not cause signature errors.
Avoid typing params only if parent/interface method has no type hint.
If you want, I can help you confirm the exact signatures for any other Yii2 methods!
User
but hte code from yii2 is this:
code
*
* @param bool $insert whether this method called while inserting a record.
* If `false`, it means the method is called while updating a record.
* @return bool whether the insertion or updating should continue.
* If `false`, the insertion or updating will be cancelled.
*/
public function beforeSave($insert)
{
$event = new ModelEvent();
$this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
return $event->isValid;
}
Assistant
Ah, thanks for clarifying — you're looking at the Yii2 source code where beforeSave() has no parameter type hint on $insert yet the PHPDoc says it is a bool.
What does this mean for your override?
If the parent method has no parameter type hint, then adding bool $insert in your override will cause a PHP fatal error because the signature becomes incompatible with the parent.
PHP requires the overriding method's parameter type hints to be the same or less strict than the parent's. Since the parent has no hint, adding bool is stricter.
So in your case:
php
// Yii2 parent:
public function beforeSave($insert)
// Your override:
public function beforeSave(bool $insert): bool // <-- parameter typed but parent is not
This causes:
code
Fatal error: Declaration of YourClass::beforeSave(bool $insert) must be compatible with BaseActiveRecord::beforeSave($insert)
What to do?
Do not add the parameter type hint for $insert if overriding a Yii2 method that does not define it.
You may add a return type hint: bool if PHP version supports it and parent allows covariant return types (Yii2 base method returns bool, so this is safe).
Use PHPDoc for parameter types:
php
/**
* @param bool $insert whether the save is an insert operation
* @return bool whether to continue saving
*/
public function beforeSave($insert): bool
{
if (!parent::beforeSave($insert)) {
return false;
}
// your code here
return true;
}
Why does Yii2 omit the parameter type hint?
To remain compatible with older PHP versions before scalar type hints were widely supported (Yii2 was designed to support PHP 5.4+).
To provide flexibility for calling code.
User
what about a custom validator for rules?
public function validateStatus(string attribute,arrayparams): void
is it ok to define
Assistant
Yes, it’s perfectly fine to add strict parameter type hints like
php
public function validateStatus(string $attribute, array $params): void
for your custom validators used in Yii2 rules(), provided:
The framework method does not declare this function in its base class or interface (custom validators are simply your own methods).
Yii2 calls your validator methods via PHP’s call_user_func() or method callback, passing exactly the expected parameters:
$attribute as string
$params as array
Explanation
Yii2 expects your validator methods to have the signature:
php
function validatorName($attribute, $params)
$attribute — the attribute name being validated (string)
$params — additional parameters supplied in rules() (array)
You are free to type the parameters as string and array for better clarity and type safety.
Yii2 will not complain because it does not enforce a formal interface or method override here — it calls the method dynamically.
Adding the : void return type is also good practice, since validators generally don’t return anything and instead add errors internally.
Example
php
public function rules()
{
return [
['status', 'validateStatus'],
];
}
/**
* Custom validator for 'status' attribute.
*
* @param string $attribute the attribute name to validate
* @param array $params additional parameters
*/
public function validateStatus(string $attribute, array $params): void
{
if (!$this->isValidStatus($this->$attribute)) {
$this->addError($attribute, 'Invalid status.');
}
}
Summary:
Yes, using typed parameters and return type in custom validators is OK and recommended.
It improves code clarity and helps detect errors early.
Yii2 calls these methods dynamically and does not enforce strict method signatures, so you are safe.
Just ensure the types match what Yii2 passes (string for attribute name and array for params).
If you want, I can help you convert other custom validators or Yii2 callbacks to typed signatures!
Not yet included in a published release.
Match your type declarations to input values: Make sure the code calling your functions provides values with correct types.
Use proper type declarations: For example, always type-hint bool for boolean flags, int for integers, etc.
Validate or cast inputs where necessary: Before calling strict-type methods, make sure your inputs are properly typed.
Update legacy code: Refactor or fix code that relies on implicit type conversions.
Summary
Strict types enforce exact type matching for arguments and return types.
They break any code that relies on implicit type coercion.
This leads to TypeError exceptions if types don't exactly match.
It encourages writing more robust and predictable code but requires careful adherence to type declarations.
If you have specific functions or errors you're encountering, feel free to share them and I can help diagnose why strict types cause issues in those cases!
function sum(int $a, int $b): int {
return $a + $b;
}
echo sum("5", 10); // Works fine — "5" coerced to 5
echo sum([1], 10); // Fatal error — array cannot be coerced to int
Example with strict_types:
php
declare(strict_types=1);
function sum(int $a, int $b): int {
return $a + $b;
}
echo sum("5", 10); // TypeError - string given, int expected
echo sum([1], 10); // TypeError same as above
Summary
PHP enforces basic type correctness always (since PHP 7).
Strict typing adds more rigorous enforcement by forbidding type coercion on scalar parameters.
Errors happen even without strict types if argument types are completely incompatible.
Adopting strict typing helps catch errors earlier and makes code less error-prone, but requires you to use exactly correct types.
If you want to avoid errors, the safest way is to:
Always pass the correct types to functions.
Use type declarations and check inputs.
Gradually enable strict types in your codebase and fix the errors that come up.
If you want I can help you check a specific function or code snippet to see what might break with or without strict types!
Add return type hint only if compatible
Regarding the return type hint: if the interface declares no return type hint, adding one such as : IdentityInterface|null in your method is only allowed in PHP 7.2+ if it's covariant and compatible according to PHP rules.
Usually, adding a more specific return type in implementations is allowed.
Adding stricter types on parameters is not allowed.
So your return type hint: : IdentityInterface|null is fine if supported by Yii2 interface and PHP version.
Why does doc say $id is string|int but interface is untyped?
Mostly for historical reasons and flexibility:
The interface accepts anything because some applications use UUID strings, others use integers.
Doc comments guide you in what you should pass for more predictable behavior, but PHP itself does not enforce this.
Summary
Do not define type hints for $id on the findIdentity() parameter to maintain compatibility with the interface.
Use docblocks to describe expected types (string|int).
You can add a return type hint (e.g., : IdentityInterface|null) if compatible.
Your code will throw fatal errors or warnings otherwise because PHP requires overridden methods to be compatible (no stricter parameter types).
Example correct declaration:
php
/**
* @param string|int $id
* @return IdentityInterface|null
*/
public static function findIdentity($id): IdentityInterface|null
{
return static::find()->where(['id' => $id])->active()->one();
}
This follows PHP's overriding rules and matches Yii2's expectations.
If you want, I can help review more methods for strict typing compatibility with Yii2 interfaces!
Summary:
Parent param hint
Your override param hint
Allowed?
none
none
yes
none
typed (e.g., bool)
no - fatal error
typed (bool)
typed (bool)
yes
TL;DR for your beforeSave() override in Yii2:
php
public function beforeSave($insert): bool
{
if (!parent::beforeSave($insert)) {
return false;
}
// your logic here
return true;
}
Do not put bool on $insert.
If you want strict types and parameter type safety, you’d have to override the entire framework method — which isn’t practical. So you must follow the framework signature exactly.
Let me know if you want help adding types in other contexts or how to safely use strict types with Yii2!