Can We Restrict PHP Variables to accept only certain type of values

Can We Restrict PHP Variables to accept only certain type of values

Content Index :

Can We Restrict PHP Variables to accept only certain type of values
Tag : php , By : Brian Cupps
Date : November 24 2020, 01:01 AM

help you fix your problem TL;DR Not directly, no. PHP is not strictly-typed. There are, however, a few workarounds that may work for you in the context of function parameters or properties of classes.
Long answer: PHP is not a strictly-typed language, but loosely-typed. You can give a variable any value you want, regardless of how it was initialized. So, you can't simply type something like int $myVar and expect $myVar = "foo"; to throw an error. But PHP does offer a few handy features to get you to the same end when dealing with function parameters or properties of a class.
class SomeClass 
    /* code here */

function foo(SomeClass $data)
    /* code here */
class SomeClass 
    private $foo = 0;

    function setFoo($val = 0)
        // force it to be an int
        if (is_integer($val) {
            $this->foo = $val;
        } else {
            // throw an error, raise an exception, or otherwise respond
class MyClass {
    private $type = 0; // we will force this to be an int
    private $string = ''; // we will force this to be a string
    private $arr = array(); // we will force this to be an array
    private $percent = 0; // we will force this to be a float in the range 0..100

    function __set($name, $value) {
        switch ($name) {
            case "type":
                $valid = is_integer($value);
            case "string":
                $valid = is_string($value);
            case "arr":
                $valid = is_array($value);
            case "percent":
                $valid = is_float($value) && $value >= 0 && $value <= 100;
                $valid = true; // allow all other attempts to set values (or make this false to deny them)

        if ($valid) {
            $this->{$name} = $value;

            // just for demonstration
            echo "pass: Set \$this->$name = ";
        } else {
            // throw an error, raise an exception, or otherwise respond

            // just for demonstration
            echo "FAIL: Cannot set \$this->$name = ";

$myObject = new MyClass();
$myObject->type = 1; // okay
$myObject->type = "123"; // fail
$myObject->string = 1; // fail
$myObject->string = "123"; // okay
$myObject->arr = 1; // fail
$myObject->arr = "123"; // fail
$myObject->arr = array("123"); // okay
$myObject->percent = 25.6; // okay
$myObject->percent = "123"; // fail
$myObject->percent = array("123"); // fail
$myObject->percent = 123456; // fail
/* @var integer */
$foo = 0; // will result in warnings if the IDE is configured properly and you try to do something like substr($foo, 1, 4);

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Restrict TextBoxField to accept only numeric values in BlackBerry

Tag : regex , By : anov
Date : March 29 2020, 07:55 AM
With these it helps Use a BasicEditField, or any of it's subclasses, include the FILTER_NUMERIC in the style parameter of the constructor:
BasicEditField numericField = new BasicEditField(FILTER_NUMERIC);

How to restrict generic function to accept only some type of classes

Tag : chash , By : Myatus
Date : March 29 2020, 07:55 AM
To fix the issue you can do Exactly as it's described in the question, this job is better handled by overload resolution:
public class C
    public A func(A obj)
        obj.x = 100;   
        return obj;

    public B func(B obj)
        obj.x = 100;   
        return obj;

interface IBase
    int x;

public class C
    public IBase func(IBase obj)
        obj.x = 100;   
        return obj;

How to restrict generic type of interface to accept only implementor class

Tag : java , By : codelurker
Date : March 29 2020, 07:55 AM
I wish did fix the issue. This is not possible in Java.
Consider if it were possible to require that the type argument of Comparable be the same as the implementing class. Then if you had a class Foo implements Comparable, and then also a class Bar extends Foo, Bar would also automatically implement Comparable by the way that inheritance in Java works. But that would violate the constraint that the implementing class is the same as the type argument, as Bar does not implement Comparable (and you can't even explicitly have Bar implement Comparable, as a class cannot implement a generic type with two different type arguments).

How to restrict textfield to accept only decimal values in swift

Tag : ios , By : Marie Ramos
Date : March 29 2020, 07:55 AM
it should still fix some issue If you want to allow just decimal number with your textField you can simply make it like this way no need to compare anything else.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text != "" || string != "" {
        let res = (textField.text ?? "") + string
        return Double(res) != nil
    return true

How to restrict function signature to only accept specific pairs of type parameters

Tag : javascript , By : anon
Date : March 29 2020, 07:55 AM
I hope this helps . Constituents in a union are not positional, so you should never rely on the position of a specific type in a union.
If you use tuples to defined F and G we then we can do something using tuples in rest parameters to get the correct signature and use a mapped type to merge the two tuples into a union of tuples:
type F = [string, number]
type G = [boolean, object]
type Merge<F extends any[], G extends any[]> = {
  [P in keyof F]: Parameters<(x: F[P], y: G extends Record<P, any> ? G[P]: never) => void> // [F[P], G[P]] would work as well byt 

type FG = Merge<F, G> // this is [string, boolean] | [number, object]
function f(...a: Merge<F, G>): any {

f('a', true)     // OK
f(1, { x: 1 })   // OK
f('a', { x: 1 }) // NOT OK
Related Posts Related QUESTIONS :
  • mysql_connect() causes page to not display (WAMP)
  • How to limit a users uploaded image size using PHP
  • What's the difference whether or not to run PHP in safe mode?
  • Logging in to a website cURL
  • Using php to create a password system with chinese characters
  • PHP is not called properly in IE using set interval function in Javascript
  • How to read pdf, ppt, xl, doc files content into a string in php/python
  • php script for currency conversion
  • In PHP... best way to turn string representation of a folder structure into nested array
  • PayPal for Indian Rupees (INR) any solution
  • PHP Deployment to Live Server
  • Ideal Multi-Developer Lamp Stack?
  • How can I save an image from a file input field using PHP & MySQL?
  • Warning: array_multisort() [function.array-multisort]: Argument #1 is expected to be an array or a sort flag in
  • Connecting to external MySQL DB from a web server not running MySQL
  • Is it possible to add custom fields to a Drupal taxonomy term?
  • PHP 6.0 - Roadmap?
  • jQuery wait for ajax call to be over before continuing
  • checkUnique function?
  • How to define an n-m relation in doctrine?
  • Sort the unsorted text file and rewrite to same text file in sorted order
  • Version control a content management system?
  • How can i run Single PHP File using apache-tomcat-6.0.18?
  • Array of objects is empty when I come to retrieve one from the array
  • PHP Library: Calculate a bounding box for a given lat/lng location
  • Good Wordpress Theme/plugin for showing off code examples and scripts
  • Replace all spaces and special symbols with dash in URL using PHP language
  • globally get any field value in user table of logged in user
  • Can you get a job if you know XHTML, CSS and Basic PHP?
  • HTML Upload Form will only upload files found in the directory of the PHP file
  • Determine if a PHP array uses keys or indices
  • Are frameworks really necessary for beginners/intermediates?
  • PHP File Downloading Questions
  • Who owns a php exec tar extracted file?
  • Best way to get timezone of user based on area code
  • Mysql BETWEEN clause being ignored. No syntax error
  • Zend Framework: Getting request object in bootstrap
  • PHP + GD: imagetruecolortopalette not keeping transparency
  • Good Guide For Web App Security?
  • Creating a new wordpress post from twitter tweets
  • Query to show images with recent posts in Wordpress sidebar/widget
  • select & print multiple value from dropdown list
  • Storing a digital signature for bookings on a web based system
  • How to generate all permutations of a string in PHP?
  • How do I get the PostgreSQL PHP extension working on Windows?
  • Parsing WordPress XML, slash:comments syntax?
  • Hide order status in the status dropdown on WooCommerce admin orders page
  • PHP Converting Hex string to Byte Array - converting VB.Net to PHP
  • Mutiple forms using same php mailer script
  • PHP replace string with value from array
  • Laravel group by issues with an inline select statement
  • Remove featured image from the WooCommerce gallery if gallery exist
  • Detect when a user changes any of their billing details (user meta)
  • Category Wise post page pagination is not working in codeigniter ..?
  • Custom checkbox show or hide custom notice in Woocommerce checkout
  • What is the maximum number of recipients for email sending in laravel?
  • How to get current time in Datetime format PHP?
  • Show or Hide content user role wise
  • How can I write to files through an agi php?
  • Cookie wont set, no result
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com