亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何區分 PHP 屬性是否未定義或設置為 NULL

如何區分 PHP 屬性是否未定義或設置為 NULL

PHP
qq_笑_17 2023-09-08 14:19:46
所以我面臨這個問題。我有一個類代表數據庫中的一條記錄(本例中為 User)。該類具有與數據庫表的列一樣多的屬性。為簡單起見,我的示例中只有三個:$id- 用戶的ID(對于注冊用戶必須設置為正整數,對于尚未保存在數據庫中的用戶對象可能設置為0)$name- 用戶名(必須為每個用戶設置,但在從數據庫加載之前可能未定義)$email- 用戶的電子郵件地址(如果用戶未提交電子郵件地址,則可能為 NULL)我的(簡化的)課程如下所示:<?phpclass User{  private $id;  private $name;  private $email;    public function __construct(int $id = 0)  {      if (!empty($id)){ $this->id = $id; }      //If $id === 0, it means that the record represented by this instance isn't saved in the database yet and the property will be filled after calling the save() method  }    public function initialize(string $name = '', $email = '')  {      //If any of the parameters isn't specified, prevent overwriting curent values      if ($name === ''){ $name = $this->name; }      if ($email === ''){ $email = $this->email; }            $this->name = $name;      $this->email = $email;  }    public function load()  {      if (!empty($this->id))      {          //Load name and e-mail from the database and save them into properties      }  }  public function save()  {      if (!empty($this->id))      {          //Update existing user record in the database       }      else      {          //Insert a new record into the table and set $this->id to the ID of the last inserted row      }  }    public function isFullyLoaded()  {      $properties = get_object_vars($this);      foreach ($properties as $property)      {          if (!isset($property)){ return false; }   //TODO - REPLACE isset() WITH SOMETHING ELSE      }      return true;  }    //Getters like getName() and getId() would come here}現在終于解決我的問題了。正如您所看到的,可以在不設置所有屬性的情況下創建此類的實例。getName()如果我想在名稱未知的情況下進行調用(未通過initialize()方法設置并且未調用 load() ),那么這是一個問題。為此,我編寫了一種方法isFullyLoaded(),該方法檢查所有屬性是否已知,如果不已知,load()則應調用(從調用的方法中調用isFullyLoaded())。問題的核心是,某些變量可能是空字符串('')、零值(0 )甚至 null (如$email屬性)。所以我想區分設置了任何值(包括 null)的變量和從未分配過任何值的變量。TL:DR PHP中如何區分未定義變量和已賦值為NULL的變量?
查看完整描述

3 回答

?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

這是引入自定義Undefined類(作為單例)的另一種方法。此外,請確保鍵入您的類屬性:


class Undefined

{

    private static Undefined $instance;


    protected function __constructor()

    {

    }


    protected function __clone()

    {

    }


    public function __wakeup()

    {

        throw new Exception("Not allowed for a singleton.");

    }


    static function getInstance(): Undefined

    {

        return self::$instance ?? (self::$instance = new static());

    }

}


class Person

{

    private int $age;


    public function getAge(): int|Undefined

    {

        return $this->age ?? Undefined::getInstance();

    }

}


$person = new Person();


if ($person->getAge() instanceof Undefined) {

    // do something

}

但使用單例模式有一個缺點,因為應用程序中所有未定義的對象將嚴格彼此相等。否則,每個返回未定義值的get 操作都會產生副作用,即另一塊分配的 RAM。


查看完整回答
反對 回復 2023-09-08
?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

PHP 不像 javascript 那樣具有未定義的值。但它不是嚴格類型的,所以如果您沒有找到更好的解決方案,這里有一個自定義類型 UNDEFINED


<?php

class UNDEFINED { }


class Test {

var $a;


    function __construct( $a='' ) {

            $this->a = new UNDEFINED();

            if( $a !== '' ) {

                    $this->a = $a;

            }

    }



    function isDefined() {

            $result =true;

            if(gettype($this->a) === 'object'){

             if(get_class($this->a) === 'UNDEFINED') {

               $result=false;

             }

            }


            echo gettype($this->a) . get_class($this->a);

            return $result;

    }


}


$test= new Test();


$test->isDefined();

這是一個可能更好的版本,它使用 instanceof 而不是 get_call 和 getType


<?php

class UNDEFINED { }


class Test {

  var $id;

  var $a;

  var $b;


  function __construct( $id) {

    $this->id = $id;

    $this->a = new UNDEFINED();

    $this->b = new UNDEFINED();

  }


  function init( $a = '' , $b = '') {

    $this->a = $this->setValue($a,$this->a);

    $this->b = $this->setValue($b,$this->b);

  }


  function setValue($a,$default) {

    return $a === '' ? $default : $a;

  }


  function isUndefined($a) {

    return $a instanceof UNDEFINED;

  }

 

  public function isFullyLoaded()

  {

    $result = true;

    $properties = get_object_vars($this);

    print_r($properties);

    foreach ($properties as $property){

      $result = $result && !$this->isUndefined($property);

      if ( !$result) break;

    }

    return $result;

  }


  function printStatus() {

    if($this->isFullyLoaded() ) {

      echo 'Loaded!';

    } else {

      echo 'Not loaded';

    }

  }

}


$test= new Test(1); 

$test->printStatus();

$test->init('hello');

$test->printStatus();

$test->init('', null);

$test->printStatus();


查看完整回答
反對 回復 2023-09-08
?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

用途property_exists():


<?php


error_reporting(E_ALL);


// oop:


class A {

    public $null_var = null;

}


$a = new A;


if(property_exists($a, 'null_var')) {

    echo "null_var property exists\n";

}


if(property_exists($a, 'unset_var')) {

    echo "unset_var property exists\n";

}


// procedural:


$null_var = null;


if(array_key_exists('null_var', $GLOBALS)) {

    echo "null_var variable exists\n";

}


if(array_key_exists('unset_var', $GLOBALS)) {

    echo "unset_var variable exists\n";

}


// output:

// null_var property exists

// null_var variable exists


查看完整回答
反對 回復 2023-09-08
  • 3 回答
  • 0 關注
  • 142 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號