reflectionproperty_isreadable

ReflectionProperty::isReadable(?string $scope, ?object $object = null): bool | ReflectionProperty::isWritable(?string $scope, ?object $object = null): bool

Per-scope readability/writability checks (new in PHP 8.6, Reflection): factoring in visibility, asymmetric visibility, hooks, __get/__set and initialization state.

C C23

C23
#include <stdio.h>

struct user {
    char *name;     /* no access modifiers — every member is public */
    char *password; /* "private" is only a naming convention */
};

int main(void) {
    /* C has neither access control nor reflection: struct members are bare.
       Real privacy is simulated with opaque pointers: expose only a forward
       declaration in the header and let accessor functions own the struct. */
    struct user u = {"Alice", "s3cret"};
    printf("%s %s\n", u.name, u.password);
    return 0;
}
Output
Alice s3cret

C++ C++26

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

class User {
public:
    std::string name = "Alice";
private:
    std::string password = "s3cret";
};

int main() {
    User u;
    std::cout << u.name << "\n";
    // u.password = compile error: private — visibility is enforced at compile time.
    // No runtime reflection to inspect it (C++26 static reflection is still landing)
    return 0;
}
Output
Alice

C# v11.0.100

v11.0.100
using System.Reflection;

// PropertyInfo.CanRead/CanWrite answer "does the accessor exist", not "who may see it"
var t = typeof(User);
foreach (var n in new[] { "Name", "Token", "Secret" })
{
    var p = t.GetProperty(n)!;
    Console.WriteLine($"{n}: CanRead={p.CanRead} CanWrite={p.CanWrite} setPublic={p.SetMethod?.IsPublic}");
}

class User
{
    public string Name { get; set; } = "";
    public string Token { get; private set; } = ""; // asymmetric visibility ≈ PHP private(set)
    public string Secret { get; init; } = "";       // init-only ≈ readonly
}
Output
Name: CanRead=True CanWrite=True setPublic=True
Token: CanRead=True CanWrite=True setPublic=False
Secret: CanRead=True CanWrite=True setPublic=True

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Name     string
	password string // unexported = package-private by naming convention
}

func main() {
	// reflect can SEE unexported fields but never write them (CanSet=false)
	u := User{Name: "Alice", password: "s3cret"}
	v := reflect.ValueOf(&u).Elem()
	fmt.Println(v.FieldByName("Name").CanSet(), v.FieldByName("password").CanSet())
	// visibility is enforced by the compiler across package borders; inside the
	// defining package the field stays plainly reachable
	fmt.Println(u.Name, u.password)
}
Output
true false
Alice s3cret

Java v27.0.1

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

class Box {
    public String name;
    private String password = "s3cret";
    public final String token = "t-1"; // final ≈ readonly: assign-once
}

public class Main {
    public static void main(String[] args) throws Exception {
        // No "can this scope read/write" API — modifiers as bits, decoded by Modifier
        // (Modifier.toString is deprecated but still the idiomatic bit-decoder)
        System.out.println(Modifier.toString(Box.class.getDeclaredField("name").getModifiers()));
        System.out.println(Modifier.toString(Box.class.getDeclaredField("password").getModifiers()));
        System.out.println(Modifier.toString(Box.class.getDeclaredField("token").getModifiers()));
        // canAccess: "would reflective access need setAccessible", not business visibility
        Box b = new Box();
        Field pw = Box.class.getDeclaredField("password");
        System.out.println(pw.canAccess(b));
    }
}
Output
public
private
public final
false

JavaScript v26.13.1

v26.13.1
// No access modifiers on plain objects; #fields are truly private — and invisible to reflection
class User {
  name = "Alice";
  #password = "s3cret"; // real privacy: not in any property table
  static leak(u) { return u.#password; } // class scope reads it fine
}
const u = new User();
console.log(u.name);
console.log(Object.keys(u));     // ["name"] — #password absent
console.log("#password" in u);   // false — not in the property namespace at all
console.log(Reflect.ownKeys(u)); // ["name"] — reflection cannot see it either
console.log(User.leak(u));       // s3cret — class scope is the only key
try { eval("u.#password"); } catch (e) { console.log(e.name); } // SyntaxError: parse-time
Output
Alice
[ 'name' ]
false
[ 'name' ]
s3cret
SyntaxError

PHP v8.6.0

v8.6.0
// ReflectionProperty::isReadable/isWritable (PHP 8.6+): "can $scope read/write this property?"
class User
{
    public string $name;
    private string $password = 'secret';
    public private(set) string $token = 't-1'; // asymmetric: everyone reads, only the class writes
}

$nameP = new ReflectionProperty(User::class, 'name');
$passP = new ReflectionProperty(User::class, 'password');
$tokP = new ReflectionProperty(User::class, 'token');
// null scope = global scope (code outside any class)
var_dump($nameP->isReadable(null), $passP->isReadable(null));
var_dump($passP->isReadable(User::class), $passP->isWritable(User::class));
var_dump($tokP->isReadable(null), $tokP->isWritable(null));
// readonly: writes flip to false once initialized (object state needed)
class Box
{
    public readonly string $v;
    public function init(string $x): void { $this->v = $x; }
}
$b = new Box();
$vP = new ReflectionProperty(Box::class, 'v');
var_dump($vP->isWritable(Box::class, $b));
$b->init('t-1');
var_dump($vP->isWritable(Box::class, $b));
Output
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)

Python v3.15.2

v3.15.2
# No access modifiers — privacy is naming convention plus one feature: name mangling
class User:
    def __init__(self):
        self.name = "Alice"        # public
        self._token = "t-1"        # single underscore: "protected" by convention only
        self.__password = "s3cret" # double underscore: mangled to _User__password

u = User()
print(u.name)
print(u._token)                    # nothing actually stops access
print(hasattr(u, "__password"), hasattr(u, "_User__password"))
print(sorted(k for k in vars(u)))
Output
Alice
t-1
False True
['_User__password', '_token', 'name']

Rust v1.99.1

v1.99.1
struct User {
    name: String,      // private by default: visible only within this module
    pub token: String, // pub widens it; pub(crate)/pub(super) give finer grains
}

impl User {
    fn new() -> Self {
        User { name: "Alice".into(), token: "t-1".into() }
    }
}

fn main() {
    // No runtime reflection at all — visibility is purely a compile-time gate
    let u = User::new();
    println!("{} {}", u.name, u.token); // same module: both readable here
}
Output
Alice t-1

TypeScript v26.13.1

v26.13.1
// TS mirrors Java-style modifiers at compile time; #fields stay private at runtime (like JS)
class User {
  name = "Alice";
  private password = "s3cret"; // erased at compile time — the property still exists at runtime
}
const u = new User();
console.log(u.name);
console.log(Object.keys(u));      // ["name", "password"] — TS private is NOT runtime privacy
console.log((u as any).password); // s3cret — a cast is all it takes
Output
Alice
[ 'name', 'password' ]
s3cret

Language differences

The spectrum of "who may read/write": PHP 8.6 makes it a first-class scope API; static languages read modifier bits/accessor metadata; dynamic languages keep only conventions — semantics differ hugely, don't map one language's intuition onto another's.

C: no access modifiers, no reflection — struct members are bare (example); "privacy" is simulated with opaque pointers plus headers that expose only a forward declaration.

C++: private enforced at compile time, no runtime reflection (example); friend is a compile-time whitelist; before C++26 static reflection lands, members are invisible at runtime.

C#: PropertyInfo.CanRead/CanWrite (example) answer only "does the accessor exist", ignoring visibility (Token's private setter still reports CanWrite=True); for "who may access" you must inspect GetMethod/SetMethod's IsPublic yourself.

Go: reflect can SEE unexported fields but CanSet=false (example) — visibility is compiler-enforced across packages, read-only at runtime; the defining package's source still reaches it directly.

Java: no first-class "may this scope access" API — Modifier bit decoding (example) plus canAccess (whether reflective access needs setAccessible, not business visibility); readonly ≈ final.

JavaScript: #fields are truly private — absent from every property table (Object.keys/Reflect.ownKeys/in all miss them, example); access outside the class body is a parse-time SyntaxError (uncatchable without eval); a different thing from TS's compile-time private.

PHP: isReadable/isWritable (new in 8.6) answer per scope (null = global scope), factoring in visibility, asymmetric visibility (private(set)), property hooks, __get/__set and initialization state (readonly flips to false once written); true does not guarantee a read succeeds (a get hook may still throw).

Python: no modifiers — underscore conventions plus double-underscore name mangling (example), the textbook "convention vs enforcement" pair; inspect gives names, never access levels.

Rust: no runtime reflection at all — visibility is a compile-time concept with pub(crate)/pub(super) module granularity (fields default to module-visible, example).

TypeScript: private is erased at compile time (the property persists at runtime, one cast away — example); real runtime privacy is a #field (same as JavaScript).