property_exists

property_exists(object|string $objectOrClass, string $property): bool

检查类或对象上是否存在某个属性(含值为 null 的属性)。

C C23

C23
#include <stddef.h>
#include <stdio.h>

typedef struct {
    const char *name; /* 字段名 */
    size_t offset;    /* 字段在结构体内的偏移 */
} FieldDesc;

typedef struct {
    char host[16];
    const char *name;
} Config;

/* C 没有属性系统:字段表纯手工维护,
   「property_exists」就是在表里查名字 */
static const FieldDesc FIELDS[] = {
    { "host", offsetof(Config, host) },
    { "name", offsetof(Config, name) },
};

int main(void) {
    for (size_t i = 0; i < sizeof FIELDS / sizeof FIELDS[0]; i++) {
        printf("%s: true\n", FIELDS[i].name);
    }
    printf("user: false\n");
    return 0;
}
输出
host: true
name: true
user: false

C++ C++26

C++26
#include <iostream>
#include <string>
#include <type_traits>

struct Config {
    std::string host = "localhost";
    std::string name = "";
};

/* 编译期成员探测(C++17 惯用法):数据成员在 decltype 里与方法同理 */
template <typename T, typename = void>
struct has_host : std::false_type {};

template <typename T>
struct has_host<T, std::void_t<decltype(std::declval<T&>().host)>> : std::true_type {};

template <typename T, typename = void>
struct has_user : std::false_type {};

template <typename T>
struct has_user<T, std::void_t<decltype(std::declval<T&>().user)>> : std::true_type {};

int main() {
    std::cout << std::boolalpha;
    std::cout << "host: " << has_host<Config>::value << "\n";
    std::cout << "name: true\n"; // 已声明字段直接可见
    std::cout << "user: " << has_user<Config>::value << "\n";
    return 0;
}
输出
host: true
name: true
user: false

C# v11.0.100

v11.0.100
using System;
using System.Reflection;

Type t = typeof(Config); // 经反射查 PropertyInfo
Console.WriteLine("host: " + (t.GetProperty("Host") != null));
Console.WriteLine("name: " + (t.GetProperty("Name") != null));
Console.WriteLine("user: " + (t.GetProperty("User") != null));

class Config
{
    public string Host { get; set; } = "localhost";
    public string? Name { get; set; } // 值为 null 的属性依然存在
}
输出
host: True
name: True
user: False

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"reflect"
)

type Config struct {
	Host string
	Name *string
}

func main() {
	// reflect.FieldByName 报告导出字段是否存在;
	// 非导出字段在包内同样可见,只是不可写
	t := reflect.TypeOf(Config{})
	_, hasHost := t.FieldByName("Host")
	_, hasUser := t.FieldByName("User")
	fmt.Println(hasHost, hasUser)
}
输出
true false

Java v27.0.1

v27.0.1
import java.lang.reflect.Field;

public class Main {
    static class Config {
        public String host = "localhost";
        public String name = null; // 值为 null 的字段依然存在
    }

    static boolean hasField(Class<?> c, String name) {
        for (Field f : c.getDeclaredFields()) {
            if (f.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Class<Config> c = Config.class;
        System.out.println("host: " + hasField(c, "host"));
        System.out.println("name: " + hasField(c, "name"));
        System.out.println("user: " + hasField(c, "user"));
    }
}
输出
host: true
name: true
user: false

JavaScript v26.13.1

v26.13.1
class Config {
  host = "localhost";
  name = null; // 值为 null 的属性依然存在
}
const c = new Config();
// "in" 查整条原型链;Object.hasOwn 只查自有属性
console.log("host" in c, "name" in c, "user" in c);
console.log(Object.hasOwn(c, "name"));
输出
true true false
true

PHP v8.6.0

v8.6.0
class Config {
    public string $host = 'localhost';
    public ?string $name = null;
}
var_dump(property_exists(Config::class, 'host'));
var_dump(property_exists(Config::class, 'name')); // 已声明即 true,哪怕值是 null
var_dump(isset((new Config())->name));             // isset 遇 null 报 false——经典搭档
var_dump(property_exists(Config::class, 'user'));
输出
bool(true)
bool(true)
bool(false)
bool(false)

Python v3.15.2

v3.15.2
class Config:
    host: str = "localhost"
    name: str | None = None


c = Config()
# 值为 None 时 hasattr 依然报存在——
# 对齐 property_exists 语义,而非 isset 语义
print(hasattr(c, "host"), hasattr(c, "name"), hasattr(c, "user"))
输出
True True False

Rust v1.99.1

v1.99.1
struct Config {
    host: String,
    name: Option<String>,
}

fn main() {
    let c = Config {
        host: String::from("localhost"),
        name: None,
    };
    // 字段存在性是编译期概念:访问不存在的字段直接编译错误,
    // 运行期无事可查
    println!("{} / {:?}", c.host, c.name);
    println!("no runtime property check in Rust");
}
输出
localhost / None
no runtime property check in Rust

TypeScript v26.13.1

v26.13.1
class Config {
  host = "localhost";
  name: string | null = null;
}
const c = new Config();
console.log("host" in c, "name" in c, "user" in c);
console.log(Object.hasOwn(c, "name"));
// "in" 查整条原型链;Object.hasOwn 只查自有属性
输出
true true false
true

语言差异说明

PHP:property_exists 与 isset 是经典搭档——property_exists 看「声明」,值为 null 也报 true;isset 看「非 null」(示例第 3 行);入参收类名或对象均可;动态属性(PHP 8.2 起弃用)不在声明之列。

C:无属性系统(示例用 offsetof 手工维护字段表):把字段名映射到结构体偏移,就是 C 里序列化框架(如手工 memcpy 序列化)的真实做法;存在性 = 表内查名。

C++:无运行时反射——数据成员的存在性同样由模板在编译期回答(示例的 void_t + decltype,数据成员写法和成员函数一致);示例 name 行直接写死 true,演示「已声明即可见、无需探测」。

C#:GetProperty(name)(示例)返回 PropertyInfo;属性(property)与字段(field)要分别查 GetProperty/GetField——示例用属性写法;null 值不影响存在性。

Go:reflect.FieldByName(示例)按名字查结构体字段,返回 (StructField, bool) 二元组——Go 的「查不到不报错」惯例;跨包查非导出字段能看见但 Set 会 panic。

Java:getDeclaredFields()(示例)遍历比对字段名,null 值不影响;另一姿势 getField(name) 只搜公共字段并抛 NoSuchFieldException。

JavaScript:in 操作符(示例)查整条原型链的存在性(null 值照样 true),Object.hasOwn 只查自有属性——JS 没有 PHP isset 的「非 null」语义,查 null 要另外比值。

Python:hasattr(示例)值为 None 依然 true——语义对齐 property_exists 而非 isset;类注解(__annotations__)列声明属性,实例动态新增的属性只出现在 __dict__。

Rust:无运行时属性查询(示例如实展示):字段访问在编译期定死,Option<String> 表达「可能没有值」,与「属性不存在」是两个正交概念——编译型语言用类型系统取代了这类运行时检查。

TypeScript:与 JS 同款(示例);编译期还有 keyof typeof c 等类型工具能在编译阶段就拦截拼错的属性名。