phpv

package
v0.0.0-...-5ceddf5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2026 License: BSD-3-Clause Imports: 19 Imported by: 14

Documentation

Overview

Package phpv contains all required types and interfaces for storing Goro values, context or compiled PHP code.

Index

Constants

View Source
const (
	// would use 1 << iota but those values come from php, so making them constants is more appropriate
	ZClassStatic           ZClassAttr = 0x001
	ZClassAbstract                    = 0x002
	ZClassImplAbstract                = 0x008 // an abstract method which has been implemented
	ZClassImplicitAbstract            = 0x010 // for classes
	ZClassExplicitAbstract            = 0x020 // for classes
	ZClassFinal                       = 0x040 // class attribute (not method)
	ZClassTrait                       = 0x80
	ZClassAnon                        = 0x100
	ZClassAnonBound                   = 0x200
	ZClassReadonly                    = 0x800
	ZClassInherited                   = 0x400

	ZClassTypeImplicitAbstract ZClassType = 0x10
	ZClassTypeExplicitAbstract            = 0x20
	ZClassTypeInterface                   = 0x40
	ZClassTypeTrait                       = 0x80
	ZClassTypeAnon                        = 0x100
	ZClassTypeEnum                        = 0x200

	ZAttrStatic         ZObjectAttr = ZObjectAttr(ZClassStatic)
	ZAttrAbstract                   = ZObjectAttr(ZClassAbstract)
	ZAttrFinal                      = 0x004 // final method, not the same value as ZClassFinal
	ZAttrPublic                     = 0x100
	ZAttrProtected                  = 0x200
	ZAttrPrivate                    = 0x400
	ZAttrAccess                     = ZAttrPublic | ZAttrProtected | ZAttrPrivate
	ZAttrImplicitPublic             = 0x1000 // method without flag
	ZAttrCtor                       = 0x2000
	ZAttrDtor                       = 0x4000
	ZAttrUserArgInfo                = 0x80    // method flag used by Closure::__invoke()
	ZAttrAllowStatic                = 0x10000 // method flag (bc only), any method that has this flag can be used statically and non statically.
	ZAttrShadow                     = 0x20000 // shadow of parent's private method/property
	ZAttrDeprecated                 = 0x40000 // deprecation flag
	ZAttrClosure                    = 0x100000
	ZAttrFakeClosure                = 0x40
	ZAttrGenerator                  = 0x800000
	ZAttrViaTrampoline              = 0x200000           // call through user function trampoline. e.g. __call, __callstatic
	ZAttrViaHandler                 = ZAttrViaTrampoline // call through internal function handler. e.g. Closure::invoke()
	ZAttrVariadic                   = 0x1000000
	ZAttrReturnRef                  = 0x4000000
	ZAttrUseGuard                   = 0x1000000  // class has magic methods __get/__set/__unset/__isset that use guards
	ZAttrHasTypeHints               = 0x10000000 // function has typed arguments
	ZAttrHasReturnType              = 0x40000000 // Function has a return type (or class has such non-private function)
	ZAttrReadonly                   = 0x08       // readonly property (PHP 8.1)
	ZAttrParenConsumed              = 0x80000000 // internal flag: opening paren was consumed during attribute parsing
)
View Source
const (
	ResourceUnknown = iota
	ResourceStream
	ResourceContext
	ResourceStreamFilter
)
View Source
const CompareUncomparable = 2

CompareUncomparable is a sentinel value returned by CompareObject when two objects cannot be ordered (e.g., different enum cases). Callers should treat this as "not equal" for == and "incomparable" (all ordered comparisons return false) for <, >, <=, >=.

Variables

View Source
var ErrComparisonDepth = errors.New("Nesting level too deep - recursive dependency?")

ErrComparisonDepth is returned when object comparison exceeds the maximum recursion depth. Callers should convert this to a PHP Error throwable.

View Source
var ErrNextElementOccupied = errors.New("Cannot add element to the array as the next element is already occupied")

ErrNextElementOccupied is returned by Append when the next integer key would overflow PHP_INT_MAX, matching PHP's "Cannot add element to the array as the next element is already occupied" error.

View Source
var NewStdClassFunc func(ctx Context) (ZObject, error)

NewStdClassFunc is a factory for creating stdClass objects. It is set by the phpobj package during init to break the cyclic dependency.

View Source
var TraceArgMaxLen = 15

TraceArgMaxLen is the default max length for string arguments in stack traces. It can be overridden via the zend.exception_string_param_max_len ini setting.

View Source
var ZFalse = ZBool(false)
View Source
var ZNULL = ZNull{}

global NULL for easy call

View Source
var ZTrue = ZBool(true)

Functions

func CallableDisplayName

func CallableDisplayName(c Callable) string

CallableDisplayName returns the display name for a Callable. For MethodCallable/BoundedCallable it includes the class prefix. For other callables it returns Name().

func ClassNameMatch

func ClassNameMatch(c ZClass, name ZString, ctx Context) bool

func Compare

func Compare(ctx Context, a, b *ZVal) (int, error)

func CompareArray

func CompareArray(ctx Context, aa, ba *ZArray) (int, error)

func CompareIntStrings

func CompareIntStrings(a, b string) int

compareIntStrings compares two integer-like strings with arbitrary precision. Both strings must consist of optional leading whitespace, optional '-', then digits. Returns -1, 0, or 1.

func CompareObject

func CompareObject(ctx Context, ao, bo ZObject) (int, error)

func DebugDump

func DebugDump(v Runnable) string

func Equals

func Equals(ctx Context, a, b *ZVal) (bool, error)

func Every

func Every(ctx Context, array *ZArray, predicate func(*ZVal) bool) bool

func ExitError

func ExitError(retcode ZInt) error

func FilterExitError

func FilterExitError(err error) error

func FormatFloat

func FormatFloat(f float64) string

FormatFloat formats a float64 value in PHP-compatible style for var_dump and similar output (serialize_precision=-1 behavior). It uses the shortest decimal representation that round-trips back to the same float64 value. PHP uses decimal form for values where -4 <= exponent < 17, and scientific notation otherwise, always ensuring a decimal point in E notation.

func FormatFloatPrecision

func FormatFloatPrecision(f float64, prec int) string

FormatFloatPrecision formats a float64 using the given precision (like PHP's precision ini setting). Used for echo/print and string casting. When prec < 0, uses PHP's "shortest unique representation" mode. When prec == 0, PHP uses 1 significant digit (minimum).

func FormatFloatSerialize

func FormatFloatSerialize(f float64) string

FormatFloatSerialize formats a float64 for serialize() when serialize_precision=0. PHP's zend_gcvt at ndigit=0 always uses scientific notation (1 significant digit in E format), matching the behavior where the sci threshold is decpt > 0.

func GetGoDebugTrace

func GetGoDebugTrace() []byte

func GetPrecision

func GetPrecision(ctx Context) int

GetPrecision reads the 'precision' INI setting from the context. Returns 14 (PHP default) if not set or context is nil.

func GetSerializePrecision

func GetSerializePrecision(ctx Context) int

GetSerializePrecision reads the 'serialize_precision' INI setting from the context. Returns -1 (PHP default) if not set or context is nil.

func IsExit

func IsExit(err error) bool

func IsNilClass

func IsNilClass(c ZClass) bool

IsNilClass checks if a ZClass interface value is nil (handles the nil pointer in non-nil interface case)

func IsNull

func IsNull(val Val) bool

func ResolveTypeHintSelf

func ResolveTypeHintSelf(h *TypeHint, className ZString) string

ResolveTypeHintSelf returns the string representation of the type hint with "self" resolved to the given class name. This is used for error messages when trait methods use "self" in their signatures.

func StrictEquals

func StrictEquals(ctx Context, a, b *ZVal) (bool, error)

func TraceArgStringMaxLen

func TraceArgStringMaxLen(arg *ZVal, maxLen int) string

TraceArgStringMaxLen formats a single argument for display in a stack trace, truncating string values to maxLen characters.

func UnwrapError

func UnwrapError(err error) error

func ZValTypeName

func ZValTypeName(z *ZVal) string

ZValTypeName returns the PHP type name of a ZVal, including the class name for objects (e.g. "stdClass" instead of just "object").

func ZValTypeNameDetailed

func ZValTypeNameDetailed(z *ZVal) string

ZValTypeNameDetailed returns the PHP 8 type name for error messages, where booleans are "true" or "false" instead of "bool".

Types

type AttrStream

type AttrStream interface {
	Attr(v interface{}) interface{}
}

type AttributeGetter

type AttributeGetter interface {
	GetAttributes() []*ZAttribute
}

AttributeGetter is implemented by callables that have PHP attributes.

type BoundedCallable

type BoundedCallable struct {
	Callable
	This ZObject
	Args []*ZVal
}

func Bind

func Bind(fn Callable, this ZObject, args ...*ZVal) *BoundedCallable

func (*BoundedCallable) AsVal

func (b *BoundedCallable) AsVal(ctx Context, t ZType) (Val, error)

func (*BoundedCallable) DisplayName

func (b *BoundedCallable) DisplayName() string

func (*BoundedCallable) GetArgs

func (b *BoundedCallable) GetArgs() []*FuncArg

func (*BoundedCallable) GetType

func (b *BoundedCallable) GetType() ZType

Override Val methods so that BoundedCallable wraps itself in ZVal instead of delegating to the embedded Callable (which would lose the wrapper).

func (*BoundedCallable) ReturnsByRef

func (b *BoundedCallable) ReturnsByRef() bool

func (*BoundedCallable) String

func (b *BoundedCallable) String() string

func (*BoundedCallable) Value

func (b *BoundedCallable) Value() Val

func (*BoundedCallable) ZVal

func (b *BoundedCallable) ZVal() *ZVal

type CallSiteLocProvider

type CallSiteLocProvider interface {
	CallSiteLoc() *Loc
}

CallSiteLocProvider is implemented by FuncContext implementations that can return the location where the function was called from (the call site), as opposed to Loc() which returns the current execution position in the parent. This is used by generator backtrace capture to record the exact call site.

type Callable

type Callable interface {
	Val
	Name() string
	Call(ctx Context, args []*ZVal) (*ZVal, error)
}

type CallableVal

type CallableVal struct{}

Used to make struct Callables satisfy the Val interface

func (CallableVal) AsVal

func (c CallableVal) AsVal(ctx Context, t ZType) (Val, error)

func (CallableVal) GetType

func (c CallableVal) GetType() ZType

func (CallableVal) Name

func (c CallableVal) Name() string

func (CallableVal) String

func (c CallableVal) String() string

func (CallableVal) Value

func (c CallableVal) Value() Val

func (CallableVal) ZVal

func (c CallableVal) ZVal() *ZVal

type Cloneable

type Cloneable interface {
	Clone() any
}

type ClosureInstanceKeyProvider

type ClosureInstanceKeyProvider interface {
	ClosureInstanceKey() uintptr
}

ClosureInstanceKeyProvider is implemented by closure instances that support per-instance static variable storage. The key uniquely identifies this specific closure instance (distinct from other closures defined in the same source).

type ClosureStaticVarKeyProvider

type ClosureStaticVarKeyProvider interface {
	ClosureStaticVarKey() uintptr
}

ClosureStaticVarKeyProvider is an optional interface implemented by FuncContext when running inside a specific closure instance. The key is a uintptr that uniquely identifies the closure instance (typically its pointer address). This is used by runStaticVar to provide per-closure-instance static variable storage.

type Compilable

type Compilable interface {
	Compile(ctx Context) error
}

type CompileDelayed

type CompileDelayed struct {
	V Runnable
}

func (*CompileDelayed) AsVal

func (c *CompileDelayed) AsVal(ctx Context, t ZType) (Val, error)

func (*CompileDelayed) GetType

func (c *CompileDelayed) GetType() ZType

func (*CompileDelayed) Run

func (c *CompileDelayed) Run(ctx Context) (*ZVal, error)

func (*CompileDelayed) String

func (c *CompileDelayed) String() string

func (*CompileDelayed) Value

func (c *CompileDelayed) Value() Val

func (*CompileDelayed) ZVal

func (c *CompileDelayed) ZVal() *ZVal

type CompoundWritable

type CompoundWritable interface {
	Writable
	IsCompoundWritable()
}

CompoundWritable is a marker interface for Writable types that represent compound expressions (array elements, object properties) rather than simple variables. These need special handling for by-ref parameter passing because the reference needs to be created and cleaned up explicitly.

type Context

type Context interface {
	context.Context
	ZArrayAccess
	ZCountable
	ZIterable
	io.Writer

	// return value of GetScriptFile will change depending on which
	// currently include()'d or require()'d file is running
	GetScriptFile() ZString

	Global() GlobalContext
	Func() FuncContext
	Parent(n int) Context
	This() ZObject
	Class() ZClass
	Loc() *Loc
	Tick(ctx Context, l *Loc) error
	MemAlloc(ctx Context, s uint64) error

	Errorf(format string, a ...any) error
	Error(err error, t ...PhpErrorType) error
	FuncErrorf(format string, a ...any) error
	FuncError(err error, t ...PhpErrorType) error

	// In the following functions, args can also take logopt types:
	// examples:
	//   Warn("testing %d", 123, logopt.NoFuncName(true))
	//   Notice("note %s", "asdf", logopt.NoLoc(true))
	//   Notice("nope", logopt.Data{NoLoc: false})
	Warn(format string, args ...any) error
	Notice(format string, args ...any) error
	Deprecated(format string, args ...any) error
	UserDeprecated(format string, args ...any) error

	LogError(err *PhpError, optionArg ...logopt.Data)

	WarnDeprecated() error

	GetFuncName() string

	GetConfig(name ZString, def *ZVal) *ZVal
	GetGlobalConfig(name ZString, def *ZVal) *ZVal

	Call(ctx Context, f Callable, args []Runnable, this ...ZObject) (*ZVal, error)
	CallZVal(ctx Context, f Callable, args []*ZVal, this ...ZObject) (*ZVal, error)
	CallZValInternal(ctx Context, f Callable, args []*ZVal, this ...ZObject) (*ZVal, error)
	CallZValNoCalledIn(ctx Context, f Callable, args []*ZVal, this ...ZObject) (*ZVal, error)

	GetStackTrace(ctx Context) []*StackTraceEntry

	HeaderContext() *HeaderContext
}

type FuncArg

type FuncArg struct {
	VarName            ZString
	Ref                bool
	PreferRef          bool // ZEND_SEND_PREFER_REF: silently accepts non-ref values (no warning)
	Required           bool
	Variadic           bool // ...param (collects remaining args into array)
	DefaultValue       Val
	DefaultValueExpr   string // PHP source representation of the default value expression (e.g. constant name), preserved for reflection
	Hint               *TypeHint
	SkipTypeCheck      bool          // if true, the Hint is used for display only (no type enforcement)
	Promotion          ZObjectAttr   // Non-zero if this is a constructor promoted property
	SetPromotion       ZObjectAttr   // PHP 8.4 asymmetric visibility for CPP (0 = same as Promotion)
	ImplicitlyNullable bool          // type hint + NULL default without explicit ?
	Attributes         []*ZAttribute // PHP 8.0 attributes
	Loc                *Loc          // Source location of this parameter

	// Property hooks for promoted properties (PHP 8.4)
	PromotionHooks *ZClassProp // non-nil if promoted property has hooks
}

type FuncCallExpression

type FuncCallExpression interface {
	IsFuncCallExpression()
}

FuncCallExpression is a marker interface for expressions that represent function/method calls. When passed to a by-reference parameter, these produce a Fatal Error in PHP 8+ ("could not be passed by reference").

type FuncContext

type FuncContext interface {
	Context
}

type FuncDeclLoc

type FuncDeclLoc interface {
	GetDeclLoc() *Loc
}

FuncDeclLoc is implemented by named function callables that know their declaration location. Used for "Cannot redeclare function" error messages.

type FuncGetArgs

type FuncGetArgs interface {
	GetArgs() []*FuncArg
}

type FuncUse

type FuncUse struct {
	VarName ZString
	Value   *ZVal
	Ref     bool
}

type GeneratorBodyCallable

type GeneratorBodyCallable interface {
	IsGeneratorBody() bool
}

GeneratorBodyCallable is implemented by callables that represent the body of a PHP generator function. Used by GetStackTrace to mark the generator function frame as [internal function] in backtraces, matching PHP's behavior.

type GeneratorCallerContext

type GeneratorCallerContext interface {
	// GetCallingTrace returns the stack trace entries from the context that
	// resumed this generator, plus a synthetic Generator->method() frame.
	// The entries should be appended after the generator's own frames.
	GetCallingTrace() []*StackTraceEntry
}

GeneratorCallerContext is implemented by generator execution contexts to provide the calling trace (the external call stack that resumed this generator). This allows GetStackTrace to build complete backtraces that include both the generator's own frames and the external invocation chain.

type GlobalContext

type GlobalContext interface {
	Context

	Flush()

	Argv() []string

	RegisterFunction(name ZString, f Callable) error
	GetFunction(ctx Context, name ZString) (Callable, error)

	RegisterShutdownFunction(f Callable)

	RegisterClass(name ZString, c ZClass) error
	UnregisterClass(name ZString)
	GetClass(ctx Context, name ZString, autoload bool) (ZClass, error)
	SetCompilingClass(c ZClass)
	GetCompilingClass() ZClass

	RegisterAutoload(handler Callable, prepend bool)
	UnregisterAutoload(handler Callable) bool
	UnregisterAutoloadByName(name string) bool
	ClearAutoloadFunctions()
	GetAutoloadFunctions() []Callable
	GetAutoloadExtensions() string
	SetAutoloadExtensions(exts string)

	RestoreConfig(name ZString)
	SetLocalConfig(name ZString, value *ZVal) (*ZVal, bool)
	IterateConfig() iter.Seq2[string, IniValue]

	ConstantSet(k ZString, v Val) bool
	ConstantGet(k ZString) (Val, bool)
	ConstantForceSet(k ZString, v Val) // overwrite even if already set
	ConstantSetAttributes(k ZString, attrs []*ZAttribute)
	ConstantGetAttributes(k ZString) []*ZAttribute

	RegisterLazyFunc(name ZString, r Runnables, p int)
	RegisterLazyClass(name ZString, r Runnables, p int)

	Open(ctx Context, fn, mode ZString, useIncludePath bool, streamCtx ...Resource) (Stream, error)
	Exists(fn ZString) (bool, error)
	Chdir(d ZString) error
	Getwd() ZString

	Getenv(key string) (string, bool)
	Setenv(key, value string) error
	Unsetenv(key string) error

	Include(ctx Context, fn ZString) (*ZVal, error)
	Require(ctx Context, fn ZString) (*ZVal, error)
	IncludeOnce(ctx Context, fn ZString) (*ZVal, error)
	RequireOnce(ctx Context, fn ZString) (*ZVal, error)

	GetLoadedExtensions() []string

	Random() *random.State

	GetUserErrorHandler() (Callable, PhpErrorType, *ZVal)
	SetUserErrorHandler(handler Callable, filter PhpErrorType, originalVal *ZVal)
	RestoreUserErrorHandler()
	SetUserExceptionHandler(handler Callable, originalVal *ZVal) *ZVal
	RestoreUserExceptionHandler()

	WriteErr(p []byte) (n int, err error)
	ShownDeprecated(key string) bool

	NextResourceID() int
	NextObjectID() int
	ReleaseObjectID(id int)

	// RegisterTempObject registers an object ID as a "temporary" that should be
	// released if it has refcount 0 at the next statement boundary.
	// isFree should return true if the object has no PHP references (refcount == 0).
	RegisterTempObject(id int, isFree func() bool)
	// DrainTempObjects checks all registered temporary objects and releases any
	// that are still unreferenced (refcount == 0). Called at statement boundaries.
	DrainTempObjects()

	GetDeclaredClasses() []ZString
	GetDefinedFunctions(ctx Context, excludeDisabled bool) (*ZArray, error)

	RegisterDestructor(obj ZObject)
	UnregisterDestructor(obj ZObject)

	CheckOpenBasedir(ctx Context, path string, funcName string) error
	IsWithinOpenBasedir(path string) bool

	// OpenFile opens a file for reading through the global file access layer.
	// This centralizes file access so it can be scoped to an fs.FS in the future.
	// The caller must close the returned ReadCloser.
	OpenFile(ctx Context, path string) (io.ReadCloser, error)

	IsUploadedFile(path string) bool
	UnregisterUploadedFile(path string)

	GetIncludedFiles() []string

	// MemMgrTracker returns the memory tracker for PHP-level allocation tracking.
	MemMgrTracker() MemTracker

	LastCallable() Callable
	ClearLastCallable()

	RegisterTickFunction(cb Callable, args []*ZVal)
	UnregisterTickFunction(cb Callable)
	CallTickFunctions(ctx Context) error
	HasTickFunctions() bool

	SetStrictTypes(v bool)
	GetStrictTypes() bool

	IsFunctionDisabled(name ZString) bool

	SetNextCallSuppressCalledIn(v bool)

	SetSkipNextDynPropDeprecation(v bool)
	TakeSkipNextDynPropDeprecation() bool
}

type HeaderContext

type HeaderContext struct {
	Sent         bool
	OutputOrigin *Loc
	Headers      http.Header
	Sender       HeaderSender
	StatusCode   int
	Callbacks    []Callable
}

func (*HeaderContext) Add

func (hc *HeaderContext) Add(key, value string, replace bool)

func (*HeaderContext) SendHeaders

func (hc *HeaderContext) SendHeaders(ctx Context) error

type HeaderSender

type HeaderSender func(headers http.Header, statusCode int) error

type HookCallable

type HookCallable struct {
	CallableVal
	Hook     Runnable
	HookName string // e.g. "MyClass::$prop::get"
	Params   []*FuncArg
}

HookCallable wraps a Runnable (property hook body) as a Callable so it can be executed via CallZVal with a proper FuncContext (which sets $this, etc). The hook body uses "return" statements to produce a value; the FuncContext's CatchReturn mechanism captures that.

func (*HookCallable) Call

func (h *HookCallable) Call(ctx Context, args []*ZVal) (*ZVal, error)

func (*HookCallable) GetArgs

func (h *HookCallable) GetArgs() []*FuncArg

func (*HookCallable) Name

func (h *HookCallable) Name() string

type IniConfig

type IniConfig interface {
	Get(name ZString) *IniValue
	CanIniSet(name ZString) bool
	RestoreConfig(ctx Context, name ZString)
	SetLocal(ctx Context, name ZString, value *ZVal) *ZVal
	SetGlobal(ctx Context, name ZString, value *ZVal) *ZVal
	IterateConfig() iter.Seq2[string, IniValue]
	Parse(ctx Context, r io.Reader) error
	EvalConfigValue(ctx Context, expr ZString) (*ZVal, error)
	LoadDefaults(ctx Context)
}

type IniValue

type IniValue struct {
	// values that are set in system php.ini or others
	Global *ZVal

	// values that are set by the user script,
	// using ini_set() or .htacess, or
	// user .ini files
	Local *ZVal
}

func (*IniValue) Get

func (iv *IniValue) Get() *ZVal

func (*IniValue) GetString

func (iv *IniValue) GetString(ctx Context) ZString

type Loc

type Loc struct {
	Filename   string
	Line, Char int
}

func (*Loc) Dump

func (l *Loc) Dump(w io.Writer) error

func (*Loc) Error

func (l *Loc) Error(ctx Context, e error, codeArg ...PhpErrorType) *PhpError

func (*Loc) Errorf

func (l *Loc) Errorf(ctx Context, code PhpErrorType, f string, arg ...interface{}) *PhpError

func (*Loc) Loc

func (l *Loc) Loc() *Loc

func (*Loc) Run

func (l *Loc) Run(ctx Context) (*ZVal, error)

func (*Loc) String

func (l *Loc) String() string

type MemTracker

type MemTracker interface {
	MemAlloc(size int64) error
	MemFree(size int64)
}

MemTracker is the interface used by ZHashTable to report memory allocation and deallocation events to the PHP memory manager.

type MethodCallable

type MethodCallable struct {
	Callable
	Class       ZClass
	CalledClass ZClass // for late static binding; nil means same as Class
	Static      bool
	AliasName   string // non-empty when the method was called via a trait alias
}

func BindClass

func BindClass(fn Callable, class ZClass, static bool) *MethodCallable

func BindClassLSB

func BindClassLSB(fn Callable, definingClass ZClass, calledClass ZClass, static bool) *MethodCallable

BindClassLSB creates a method callable with separate defining and called classes for late static binding support.

func (*MethodCallable) AsVal

func (m *MethodCallable) AsVal(ctx Context, t ZType) (Val, error)

func (*MethodCallable) DisplayName

func (m *MethodCallable) DisplayName() string

DisplayName returns the fully-qualified callable name for display purposes (e.g. ob_get_status, ob_list_handlers). Unlike Name(), this includes the class prefix for methods.

func (*MethodCallable) GetArgs

func (m *MethodCallable) GetArgs() []*FuncArg

func (*MethodCallable) GetType

func (m *MethodCallable) GetType() ZType

Override Val methods so that MethodCallable wraps itself in ZVal properly.

func (*MethodCallable) Loc

func (m *MethodCallable) Loc() *Loc

func (*MethodCallable) Name

func (m *MethodCallable) Name() string

func (*MethodCallable) ReturnsByRef

func (m *MethodCallable) ReturnsByRef() bool

func (*MethodCallable) String

func (m *MethodCallable) String() string

func (*MethodCallable) Value

func (m *MethodCallable) Value() Val

func (*MethodCallable) ZVal

func (m *MethodCallable) ZVal() *ZVal

type NamedArgument

type NamedArgument interface {
	ArgName() ZString
	Inner() Runnable
}

NamedArgument is implemented by Runnable types that represent PHP 8.0 named arguments.

type ParenthesizedExpression

type ParenthesizedExpression interface {
	IsParenthesizedExpression()
}

ParenthesizedExpression is a marker interface for parenthesized expressions. When passed to a by-reference parameter, these produce a Notice ("Only variables should be passed by reference") rather than a Fatal Error.

type PhpError

type PhpError struct {
	Err      error
	FuncName string
	Code     PhpErrorType
	Loc      *Loc

	PhpStackTrace StackTrace
	GoStackTrace  []byte

	IsInternal bool // true when error originates from internal (non-userspace) code
}

func (*PhpError) CanBeUserHandled

func (e *PhpError) CanBeUserHandled() bool

func (*PhpError) Error

func (e *PhpError) Error() string

func (*PhpError) IsExit

func (e *PhpError) IsExit() bool

func (*PhpError) IsNonFatal

func (e *PhpError) IsNonFatal() bool

type PhpErrorType

type PhpErrorType int
const (
	E_ERROR PhpErrorType = 1 << iota
	E_WARNING
	E_PARSE
	E_NOTICE
	E_CORE_ERROR
	E_CORE_WARNING
	E_COMPILE_ERROR
	E_COMPILE_WARNING
	E_USER_ERROR
	E_USER_WARNING
	E_USER_NOTICE
	E_STRICT // deprecated since PHP 8.0, removed in 8.4
	E_RECOVERABLE_ERROR
	E_DEPRECATED
	E_USER_DEPRECATED
	// E_ALL excludes E_STRICT (removed in PHP 8.4)
	E_ALL PhpErrorType = (1 << iota) - 1 - E_STRICT
)

type PhpExit

type PhpExit struct {
	// contains filtered or unexported fields
}

func (*PhpExit) Dump

func (e *PhpExit) Dump(w io.Writer) error

func (*PhpExit) Error

func (e *PhpExit) Error() string

func (*PhpExit) Loc

func (e *PhpExit) Loc() *Loc

func (*PhpExit) Run

func (e *PhpExit) Run(ctx Context) (*ZVal, error)

type PreEvaluatedArg

type PreEvaluatedArg interface {
	IsPreEvaluatedArg()
}

PreEvaluatedArg is a marker interface for pre-evaluated arguments (e.g., those passed via call_user_func). When passed to a by-reference parameter, these produce a Warning ("FuncName(): Argument #N must be passed by reference, value given") rather than a Notice or Fatal Error.

type ReadonlyRefChecker

type ReadonlyRefChecker interface {
	CheckReadonlyRef(ctx Context) error
}

ReadonlyRefChecker is implemented by Runnable types (like object property access) that can check whether creating a reference would violate readonly constraints. Used by the by-ref parameter passing code to throw "Cannot indirectly modify readonly property" before making a reference.

type Resource

type Resource interface {
	Val
	GetResourceType() ResourceType
	GetResourceID() int
}

type ResourceType

type ResourceType int

func (ResourceType) String

func (rs ResourceType) String() string

type RunNull

type RunNull struct{}

func (RunNull) Dump

func (r RunNull) Dump(w io.Writer) error

func (RunNull) Run

func (r RunNull) Run(ctx Context) (*ZVal, error)

type Runnable

type Runnable interface {
	Run(Context) (*ZVal, error)
	Dump(io.Writer) error
}

type RunnableChild

type RunnableChild interface {
	Runnable
	GetParentNode() Runnable
	SetParentNode(Runnable)
}

type Runnables

type Runnables []Runnable

func (Runnables) Dump

func (r Runnables) Dump(w io.Writer) error

func (Runnables) DumpWith

func (r Runnables) DumpWith(w io.Writer, sep []byte) error

func (Runnables) Run

func (r Runnables) Run(ctx Context) (l *ZVal, err error)

type SpreadArgument

type SpreadArgument interface {
	Inner() Runnable
}

SpreadArgument is implemented by Runnable types that represent argument unpacking: func(...$arr)

type StackTrace

type StackTrace []*StackTraceEntry

func (StackTrace) FormatNoMainOpts

func (st StackTrace) FormatNoMainOpts(ignoreArgs bool) ZString

FormatNoMainOpts formats without {main}, optionally ignoring args. Used by debug_print_backtrace() when DEBUG_BACKTRACE_IGNORE_ARGS is set.

func (StackTrace) FormatWithMaxLen

func (st StackTrace) FormatWithMaxLen(maxLen int) ZString

FormatWithMaxLen formats the stack trace with a custom string param max length.

func (StackTrace) String

func (st StackTrace) String() ZString

func (StackTrace) StringNoMain

func (st StackTrace) StringNoMain() ZString

StringNoMain formats the stack trace without the trailing {main} entry, as used by debug_print_backtrace().

type StackTraceEntry

type StackTraceEntry struct {
	FuncName     string
	BareFuncName string // just the method/function name without class prefix
	Filename     string
	ClassName    string
	MethodType   string
	Line         int
	Args         []*ZVal
	Object       ZObject // the $this object for instance method calls
	IsInternal   bool    // true when called from internal code (e.g., output buffer callbacks)
}

type StaticVarEntry

type StaticVarEntry struct {
	Name ZString
	Val  *ZVal
}

StaticVarEntry represents a single static variable entry with its name and current value.

type StaticVarGetter

type StaticVarGetter interface {
	GetStaticVars(ctx Context) []StaticVarEntry
}

StaticVarGetter is implemented by user-defined functions (ZClosure) to expose their static variables for ReflectionFunction::getStaticVariables(). Returns an ordered slice of name-value pairs (declaration order).

type Stream

type Stream interface {
	Resource
	Read(p []byte) (int, error)
	Write(p []byte) (n int, err error)
	Seek(offset int64, whence int) (int64, error)
	ReadByte() (byte, error)
	Close() error
	SetAttr(k string, v interface{})
	Attr(v interface{}) interface{}
	Stat() (os.FileInfo, error)
	Flush() error
	Sync() error
}

type TypeHint

type TypeHint struct {
	Nullable     bool        // true if the type is explicitly nullable (?Type)
	Union        []*TypeHint // for union types (int|string), each alternative
	Intersection []*TypeHint // for intersection types (A&B), all must match
	// contains filtered or unexported fields
}

func ParseTypeHint

func ParseTypeHint(s ZString) *TypeHint

ParseTypeHint converts a type name string to a TypeHint struct. It supports union types like "int|string" and nullable types like "?int".

func (*TypeHint) Check

func (h *TypeHint) Check(ctx Context, val *ZVal) bool

Check returns true if the value matches this type hint

func (*TypeHint) CheckStrict

func (h *TypeHint) CheckStrict(ctx Context, val *ZVal) bool

CheckStrict returns true if the value matches this type hint using strict_types rules. In strict mode, only exact type matches are allowed (no coercion), except: - int is accepted for float parameters (int-to-float widening) - null is accepted for nullable parameters

func (*TypeHint) ClassName

func (h *TypeHint) ClassName() ZString

func (*TypeHint) IsNullable

func (h *TypeHint) IsNullable() bool

IsNullable returns true if the type hint accepts null values. This includes explicitly nullable types (?Type), union types containing null, and the mixed type (which implicitly accepts null).

func (*TypeHint) String

func (h *TypeHint) String() string

String returns the PHP type name for error messages

func (*TypeHint) Type

func (h *TypeHint) Type() ZType

type UndefinedChecker

type UndefinedChecker interface {
	IsUnDefined(ctx Context) bool
	VarName() ZString
}

UndefinedChecker is implemented by Runnable types that represent simple variable accesses (e.g. $foo). It allows callers to check whether the variable is defined before evaluating the expression — useful for emitting "Undefined variable" warnings when passing undefined vars to functions.

type Val

type Val interface {
	GetType() ZType                          // GetType returns the type of the value
	ZVal() *ZVal                             // ZVal returns a ZVal pointing to this value
	Value() Val                              // Value returns the raw value, in case it was in a ZVal
	AsVal(ctx Context, t ZType) (Val, error) // AsVal converts the value to another type
	String() string                          // String should only be used on ZtString values
}

Val is a basic value of any PHP kind: null, bool, int, float, string, array, resource or object.

type Writable

type Writable interface {
	WriteValue(ctx Context, value *ZVal) error
}

type WriteContextSetter

type WriteContextSetter interface {
	SetWriteContext(bool)
}

WriteContextSetter is implemented by Runnable types (like array access expressions) that can be put into write context to suppress warnings during auto-vivification. Used when passing array elements by reference.

type WritePreparable

type WritePreparable interface {
	PrepareWrite(ctx Context) error
}

WritePreparable is implemented by Writable types that have sub-expressions (e.g. array indices, variable-variable names) which need to be evaluated before the RHS of an assignment. This ensures correct PHP evaluation order where LHS side effects happen before RHS evaluation.

type ZArray

type ZArray struct {
	// contains filtered or unexported fields
}

func NewZArray

func NewZArray() *ZArray

func NewZArrayTracked

func NewZArrayTracked(mt MemTracker) *ZArray

NewZArrayTracked creates a new ZArray with memory tracking enabled. The tracker is notified when elements are added or removed.

func (*ZArray) AsVal

func (a *ZArray) AsVal(ctx Context, t ZType) (Val, error)

func (*ZArray) ByteArrayKeys

func (a *ZArray) ByteArrayKeys(ctx Context) [][]byte

func (*ZArray) Clear

func (a *ZArray) Clear(ctx Context) error

func (*ZArray) Count

func (a *ZArray) Count(ctx Context) ZInt

func (*ZArray) DecRefObjects

func (a *ZArray) DecRefObjects(ctx Context) error

DecRefObjects decrements the reference count of all ZObject values stored in this array. Used by foreach cleanup after IncRefObjects. Returns the last error from any destructor that fired.

func (*ZArray) DeepCopy

func (a *ZArray) DeepCopy() *ZArray

DeepCopy creates an immediate independent copy without using COW. The original array's iterators remain stable.

func (*ZArray) DeepCopyStripRefs

func (a *ZArray) DeepCopyStripRefs(ctx Context) *ZArray

DeepCopyStripRefs creates a deep copy of the array with all references resolved to plain values. Used by define() to snapshot constant arrays.

func (*ZArray) Dup

func (a *ZArray) Dup() *ZArray

func (*ZArray) Empty

func (a *ZArray) Empty(ctx Context) error

Similar to Clear, but still allows iteration over deleted items

func (*ZArray) Equals

func (a *ZArray) Equals(ctx Context, b *ZArray) bool

func (*ZArray) GetType

func (a *ZArray) GetType() ZType

func (*ZArray) H

func (a *ZArray) H() *ZHashTable

H returns the underlying ZHashTable for direct access.

func (*ZArray) HasStringKeys

func (a *ZArray) HasStringKeys() bool

func (*ZArray) HashTable

func (a *ZArray) HashTable() *ZHashTable

func (*ZArray) IncRefObjects

func (a *ZArray) IncRefObjects()

IncRefObjects increments the reference count of all ZObject values stored in this array. Used by foreach to keep array elements alive while they are being iterated (preventing premature destruction).

func (*ZArray) IntKeys

func (a *ZArray) IntKeys(ctx Context) []ZInt

func (*ZArray) IsRecursive

func (a *ZArray) IsRecursive() bool

IsRecursive checks if the array contains a reference to itself (directly or indirectly).

func (*ZArray) Iterate

func (a *ZArray) Iterate(ctx Context) iter.Seq2[*ZVal, *ZVal]

func (*ZArray) IterateRaw

func (a *ZArray) IterateRaw(ctx Context) iter.Seq2[*ZVal, *ZVal]

IterateRaw returns an iterator that yields raw ZVals from the hash table without copying, preserving reference wrappers. Used by serialize() to detect PHP references (& references) between values.

func (*ZArray) MainIterator

func (a *ZArray) MainIterator() ZIterator

func (*ZArray) MergeArray

func (a *ZArray) MergeArray(b *ZArray) error

func (*ZArray) MergeTable

func (a *ZArray) MergeTable(h *ZHashTable) error

func (*ZArray) NewIterator

func (a *ZArray) NewIterator() ZIterator

func (*ZArray) OffsetAt

func (a *ZArray) OffsetAt(ctx Context, index int) (*ZVal, *ZVal, error)

func (*ZArray) OffsetCheck

func (a *ZArray) OffsetCheck(ctx Context, key Val) (*ZVal, bool, error)

func (*ZArray) OffsetContains

func (a *ZArray) OffsetContains(ctx Context, val Val) (bool, error)

func (*ZArray) OffsetExists

func (a *ZArray) OffsetExists(ctx Context, key Val) (bool, error)

func (*ZArray) OffsetGet

func (a *ZArray) OffsetGet(ctx Context, key Val) (*ZVal, error)

func (*ZArray) OffsetGetWarn

func (a *ZArray) OffsetGetWarn(ctx Context, key Val) (*ZVal, error)

OffsetGetWarn is like OffsetGet but produces a warning for undefined keys (used by user-level array access)

func (*ZArray) OffsetKeyAt

func (a *ZArray) OffsetKeyAt(ctx Context, index int) (*ZVal, error)

func (*ZArray) OffsetSet

func (a *ZArray) OffsetSet(ctx Context, key Val, value *ZVal) error

func (*ZArray) OffsetUnset

func (a *ZArray) OffsetUnset(ctx Context, key Val) error

func (*ZArray) Reset

func (a *ZArray) Reset(ctx Context)

func (*ZArray) SeparateCow

func (a *ZArray) SeparateCow()

SeparateCow forces copy-on-write separation if needed. This must be called before taking references to hash table entries (e.g., for by-ref spread) to avoid modifying data shared with other arrays.

func (*ZArray) StrictEquals

func (a *ZArray) StrictEquals(ctx Context, b *ZArray) bool

StrictEquals compares two arrays with strict comparison (===). Same keys in the same order, with values compared strictly. References are transparent (dereferenced before comparison).

func (*ZArray) String

func (a *ZArray) String() string

func (*ZArray) StringKeys

func (a *ZArray) StringKeys(ctx Context) []ZString

func (*ZArray) Value

func (a *ZArray) Value() Val

func (*ZArray) WouldOverflow

func (a *ZArray) WouldOverflow() bool

WouldOverflow returns true if the next $arr[] = append would fail with ErrNextElementOccupied (PHP_INT_MAX key slot occupied).

func (*ZArray) ZVal

func (a *ZArray) ZVal() *ZVal

type ZArrayAccess

type ZArrayAccess interface {
	OffsetGet(ctx Context, key Val) (*ZVal, error)
	OffsetSet(ctx Context, key Val, value *ZVal) error
	OffsetUnset(ctx Context, key Val) error
	OffsetExists(ctx Context, key Val) (bool, error)
	OffsetCheck(ctx Context, key Val) (*ZVal, bool, error)
}

type ZAttribute

type ZAttribute struct {
	ClassName   ZString    // fully qualified attribute class name
	Args        []*ZVal    // evaluated arguments (nil if no args)
	ArgExprs    []Runnable // unevaluated argument expressions for lazy evaluation (nil if fully resolved)
	ArgNames    []ZString  // named argument names parallel to Args (empty string = positional)
	Resolving   bool       // true while lazy args are being resolved (prevents re-entrant deprecation)
	StrictTypes bool       // true if declare(strict_types=1) was in effect at the declaration site
}

ZAttribute represents a PHP attribute (e.g. #[MyAttribute(args...)]).

type ZBool

type ZBool bool

func (ZBool) AsVal

func (z ZBool) AsVal(ctx Context, t ZType) (Val, error)

func (ZBool) GetType

func (z ZBool) GetType() ZType

func (ZBool) String

func (z ZBool) String() string

func (ZBool) Value

func (z ZBool) Value() Val

func (ZBool) ZVal

func (z ZBool) ZVal() *ZVal

type ZClass

type ZClass interface {
	GetName() ZString
	InstanceOf(parent ZClass) bool
	Implements(intf ZClass) bool
	BaseName() ZString
	GetStaticProps(ctx Context) (*ZHashTable, error)
	GetProp(name ZString) (*ZClassProp, bool)
	GetMethod(name ZString) (*ZClassMethod, bool)
	GetMethods() map[ZString]*ZClassMethod
	GetType() ZClassType
	Handlers() *ZClassHandlers
	GetParent() ZClass
	NextInstanceID() int
}

type ZClassAttr

type ZClassAttr int

func (ZClassAttr) Has

func (a ZClassAttr) Has(c ZClassAttr) bool

func (ZClassAttr) String

func (a ZClassAttr) String() string

type ZClassConst

type ZClassConst struct {
	Value          Val
	Modifiers      ZObjectAttr
	Resolving      bool          // true while the constant is being resolved (circular reference detection)
	Attributes     []*ZAttribute // PHP 8.0 attributes
	TypeHint       *TypeHint     // PHP 8.3 typed class constants
	DocComment     ZString       // doc comment (/** ... */) associated with this constant
	DeclaringClass ZClass        // the class that originally declared this constant (nil = same class)
}

type ZClassHandlers

type ZClassHandlers struct {
	Constructor        *ZClassMethod
	HandleInvoke       func(ctx Context, o ZObject, args []Runnable) (*ZVal, error)
	HandleDecRef       func(ctx Context, o ZObject)                         // called when object refcount is decremented during scope cleanup
	HandleCastArray    func(ctx Context, o ZObject) (*ZArray, error)        // override (array) cast
	HandleCompare      func(ctx Context, a, b ZObject) (int, error)         // override == comparison; return 0=equal, non-0=not-equal
	HandleCast         func(ctx Context, o ZObject, t ZType) (Val, error)   // override type casting (int, float, bool)
	HandleDoOperation  func(ctx Context, op int, a, b *ZVal) (*ZVal, error) // override arithmetic/bitwise operators; op is tokenizer.ItemType
	HandleForeachByRef func(ctx Context, o ZObject) (*ZArray, error)        // provide internal array for foreach by-reference (e.g., ArrayObject/ArrayIterator)
	// HandleIssetDim overrides isset($obj[$key]) behavior. Return true if the key exists
	// and the value is considered "set" (not null). Only called for isset(), not for direct
	// offsetExists() calls.
	HandleIssetDim func(ctx Context, o ZObject, key *ZVal) (bool, error)
	// HandleReadDim provides internal dimension read without going through PHP-level offsetGet.
	// Used by empty() to get values without triggering user-level method calls.
	HandleReadDim func(ctx Context, o ZObject, key *ZVal) (*ZVal, error)
	// HandlePropGet intercepts property read access before __get. Return (nil, nil) to fall through to normal handling.
	// If HandlePropGetEager is true, HandlePropGet is called before hash table lookup (intercepts ALL property reads).
	HandlePropGetEager bool
	HandlePropGet      func(ctx Context, o ZObject, key ZString) (*ZVal, error)
	// HandlePropSet intercepts property write access before __set. Return false to fall through to normal handling.
	HandlePropSet func(ctx Context, o ZObject, key ZString, value *ZVal) (bool, error)
	// HandlePropIsset intercepts isset($obj->prop) before __isset. Return (false, false, nil) to fall through.
	// First bool is the isset result, second bool indicates whether the handler handled it.
	HandlePropIsset func(ctx Context, o ZObject, key ZString) (bool, bool, error)
	// HandlePropUnset intercepts unset($obj->prop) before __unset. Return false to fall through.
	HandlePropUnset func(ctx Context, o ZObject, key ZString) (bool, error)
	// DenySerialize, when true, causes serialization to throw an Exception with
	// "Serialization of 'ClassName' is not allowed". This is checked before any
	// PHP-level __serialize method, so subclass overrides are ignored.
	DenySerialize bool
	// DenyUnserialize, when true, causes unserialization to throw an Exception with
	// "Unserialization of 'ClassName' is not allowed". Checked before __unserialize.
	DenyUnserialize bool
}

type ZClassMethod

type ZClassMethod struct {
	Name                ZString
	Modifiers           ZObjectAttr
	Method              Callable
	Class               ZClass
	Empty               bool
	Loc                 *Loc
	LocEnd              *Loc          // end line of the method body
	Attributes          []*ZAttribute // PHP 8.0 attributes
	FromTrait           ZClass        // non-nil if this method was imported from a trait
	Prototype           ZClass        // interface/class that defines the prototype for this method
	ReturnType          *TypeHint     // return type hint for the method (for reflection)
	TentativeReturnType bool          // if true, ReturnType is a tentative return type (PHP 8.1)
	DocComment          ZString       // doc comment (/** ... */) associated with this method
}

type ZClassProp

type ZClassProp struct {
	VarName      ZString
	Default      Val
	Modifiers    ZObjectAttr
	SetModifiers ZObjectAttr // PHP 8.4 asymmetric visibility: separate write visibility (0 = same as Modifiers)
	TypeHint     *TypeHint
	Attributes   []*ZAttribute // PHP 8.0 attributes
	DocComment   ZString       // doc comment (/** ... */) associated with this property

	// Property hooks (PHP 8.4)
	GetHook         Runnable      // get { ... } hook body
	SetHook         Runnable      // set($value) { ... } hook body
	SetParam        ZString       // parameter name for set hook (default "$value")
	HasHooks        bool          // true if property declared with hook syntax (even abstract)
	IsBacked        bool          // true if hooks reference $this->prop (backing store exists)
	GetIsAbstract   bool          // true if get hook is abstract (get;)
	SetIsAbstract   bool          // true if set hook is abstract (set;)
	GetIsFinal      bool          // true if get hook is declared final
	SetIsFinal      bool          // true if set hook is declared final
	HasGetDeclared  bool          // true if get hook was declared (even abstract)
	HasSetDeclared  bool          // true if set hook was declared (even abstract)
	SetParamHasType bool          // true if set hook parameter has explicit type hint
	GetHookLoc      *Loc          // source location of get hook declaration
	SetHookLoc      *Loc          // source location of set hook declaration
	GetHookLocEnd   *Loc          // end source location of get hook
	SetHookLocEnd   *Loc          // end source location of set hook
	GetHookAttrs    []*ZAttribute // attributes on get hook
	SetHookAttrs    []*ZAttribute // attributes on set hook
}

func (*ZClassProp) IsVirtual

func (p *ZClassProp) IsVirtual() bool

IsVirtual returns true if this property is virtual (has hooks but no backing store). A property is virtual if: - It has hooks, AND - It has no default value, AND - Its hooks never reference the backing store ($this->propName). The IsBacked flag is set at compile time by analyzing the hook bodies.

type ZClassTraitAlias

type ZClassTraitAlias struct {
	TraitName  ZString     // optional: the trait the method belongs to
	MethodName ZString     // original method name
	NewName    ZString     // alias name (empty = just visibility change)
	NewAttr    ZObjectAttr // new visibility (0 = unchanged)
}

ZClassTraitAlias represents a trait alias or visibility change: "TraitName::method as [visibility] newname"

type ZClassTraitInsteadof

type ZClassTraitInsteadof struct {
	TraitName  ZString   // the trait whose method wins
	MethodName ZString   // the method name being resolved
	InsteadOf  []ZString // traits whose methods are excluded
}

ZClassTraitInsteadof represents "TraitName::method insteadof OtherTrait [, OtherTrait2]"

type ZClassTraitUse

type ZClassTraitUse struct {
	TraitNames []ZString
	Aliases    []ZClassTraitAlias
	Insteadof  []ZClassTraitInsteadof
}

ZClassTraitUse represents a single "use TraitA, TraitB { ... }" statement in a class body.

type ZClassType

type ZClassType int

func (ZClassType) Has

func (a ZClassType) Has(c ZClassType) bool

func (ZClassType) IsInterface

func (a ZClassType) IsInterface() bool

type ZClosure

type ZClosure interface {
	FuncGetArgs
	Callable
	Runnable

	GetClass() ZClass
	IsStatic() bool   // true for static function() {} and static fn() =>
	GetThis() ZObject // the captured $this (nil for static closures / free functions)
}

type ZCountable

type ZCountable interface {
	Count(ctx Context) ZInt
}

type ZFloat

type ZFloat float64

func (ZFloat) AsVal

func (z ZFloat) AsVal(ctx Context, t ZType) (Val, error)

func (ZFloat) GetType

func (z ZFloat) GetType() ZType

func (ZFloat) String

func (v ZFloat) String() string

func (ZFloat) Value

func (v ZFloat) Value() Val

func (ZFloat) ZVal

func (z ZFloat) ZVal() *ZVal

type ZHashTable

type ZHashTable struct {
	// contains filtered or unexported fields
}

func NewHashTable

func NewHashTable() *ZHashTable

func (*ZHashTable) AdjustNextIntKeyAfterPop

func (z *ZHashTable) AdjustNextIntKeyAfterPop(poppedKey ZInt)

AdjustNextIntKeyAfterPop adjusts the next integer key counter after removing an element with array_pop(). In PHP, if the popped key was an integer and equals nNextFreeElement - 1, nNextFreeElement is decremented to match the popped key, preserving negative index behavior.

func (*ZHashTable) Append

func (z *ZHashTable) Append(v *ZVal) error

func (*ZHashTable) Array

func (z *ZHashTable) Array() *ZArray

func (*ZHashTable) Clear

func (z *ZHashTable) Clear()

func (*ZHashTable) Count

func (z *ZHashTable) Count() ZInt

func (*ZHashTable) DeepCopy

func (z *ZHashTable) DeepCopy() *ZHashTable

DeepCopy creates an immediate independent copy of the hash table without using COW. The original is not marked as COW so its iterators remain stable. This is used by ArrayIterator and similar structures that need an independent copy while keeping their iterators pointing at the correct entries.

func (*ZHashTable) Dup

func (z *ZHashTable) Dup() *ZHashTable

func (*ZHashTable) Empty

func (z *ZHashTable) Empty()

Similar to Clear, but doesn't set the deleted flag

func (*ZHashTable) ForceSetString

func (z *ZHashTable) ForceSetString(k ZString, v *ZVal) error

ForceSetString replaces the ZVal for a key entirely, bypassing the reference-preserving behavior of Set(). This is used by unserialize() to overwrite properties that may be references without updating through them.

func (*ZHashTable) GetInt

func (z *ZHashTable) GetInt(k ZInt) *ZVal

func (*ZHashTable) GetMemTracker

func (z *ZHashTable) GetMemTracker() MemTracker

GetMemTracker returns the current memory tracker (may be nil).

func (*ZHashTable) GetString

func (z *ZHashTable) GetString(k ZString) *ZVal

func (*ZHashTable) GetStringB

func (z *ZHashTable) GetStringB(k ZString) (*ZVal, bool)

func (*ZHashTable) HasInt

func (z *ZHashTable) HasInt(k ZInt) bool

func (*ZHashTable) HasString

func (z *ZHashTable) HasString(k ZString) bool

func (*ZHashTable) HasStringKeys

func (z *ZHashTable) HasStringKeys() bool

func (*ZHashTable) LastIntKey

func (z *ZHashTable) LastIntKey() (ZInt, bool)

LastIntKey returns the integer key of the last element in the hash table. Used by WriteValue after appending with [] to find the newly created element.

func (*ZHashTable) MergeTable

func (z *ZHashTable) MergeTable(b *ZHashTable) error

func (*ZHashTable) NewIterator

func (z *ZHashTable) NewIterator() ZIterator

func (*ZHashTable) RecalcNextIntKey

func (z *ZHashTable) RecalcNextIntKey()

RecalcNextIntKey recalculates the next integer key counter (inc) based on the current maximum integer key in the hash table. This is needed after operations like array_pop() that remove elements from the end.

func (*ZHashTable) ResetIntKeys

func (z *ZHashTable) ResetIntKeys()

modifies all int indices such that the first one starts with zero

func (*ZHashTable) SameData

func (z *ZHashTable) SameData(other *ZHashTable) bool

SameData returns true if this hash table shares the same underlying data as another hash table (i.e., they are COW copies of the same array). This is used for detecting circular references during serialization.

func (*ZHashTable) SeparateCow

func (z *ZHashTable) SeparateCow()

SeparateCow forces a copy-on-write separation if needed. This should be called before creating iterators that will be used alongside write operations on the same hash table (e.g., foreach by-reference), so the iterator points to the post-copy entries rather than pre-copy entries that get orphaned.

func (*ZHashTable) SetInt

func (z *ZHashTable) SetInt(k ZInt, v *ZVal) error

func (*ZHashTable) SetMemTracker

func (z *ZHashTable) SetMemTracker(mt MemTracker)

SetMemTracker sets the memory tracker for this hash table. When set, the hash table reports element additions and removals.

func (*ZHashTable) SetString

func (z *ZHashTable) SetString(k ZString, v *ZVal) error

func (*ZHashTable) Shift

func (z *ZHashTable) Shift() *ZVal

Shift removes the first element from the hash table and re-indexes integer keys starting from 0. Returns the removed value, or nil if empty. This modifies the hash table in-place so iterators remain connected.

func (*ZHashTable) UnsetInt

func (z *ZHashTable) UnsetInt(k ZInt) error

func (*ZHashTable) UnsetString

func (z *ZHashTable) UnsetString(k ZString) error

func (*ZHashTable) Unshift

func (z *ZHashTable) Unshift(values []*ZVal)

Unshift prepends values to the beginning of the hash table and re-indexes integer keys. This modifies the hash table in-place so iterators stay connected.

func (*ZHashTable) WouldOverflow

func (z *ZHashTable) WouldOverflow() bool

WouldOverflow returns true if the next Append call would fail with ErrNextElementOccupied. Used to pre-check overflow before evaluating the RHS of an assignment.

type ZInt

type ZInt int64

func FloatToIntImplicit

func FloatToIntImplicit(ctx Context, f ZFloat) (ZInt, error)

FloatToIntImplicit converts a float to int for implicit conversion contexts (bitwise ops, array offsets, modulo, function args with int type, etc.). It emits the PHP 8.1+ "Deprecated: Implicit conversion from float X to int loses precision" when the float has a non-zero fractional part.

func (ZInt) AsVal

func (z ZInt) AsVal(ctx Context, t ZType) (Val, error)

func (ZInt) GetType

func (z ZInt) GetType() ZType

func (ZInt) String

func (v ZInt) String() string

func (ZInt) Value

func (v ZInt) Value() Val

func (ZInt) ZVal

func (z ZInt) ZVal() *ZVal

type ZIterable

type ZIterable interface {
	NewIterator() ZIterator
}

type ZIterator

type ZIterator interface {
	Current(ctx Context) (*ZVal, error)
	Key(ctx Context) (*ZVal, error)
	Next(ctx Context) (*ZVal, error)
	Prev(ctx Context) (*ZVal, error)
	Reset(ctx Context) (*ZVal, error)
	ResetIfEnd(ctx Context) (*ZVal, error)
	End(ctx Context) (*ZVal, error)
	Valid(ctx Context) bool
	Iterate(ctx Context) iter.Seq2[*ZVal, *ZVal]
	IterateRaw(ctx Context) iter.Seq2[*ZVal, *ZVal]
}

type ZNull

type ZNull struct{}

scalar stuff

func (ZNull) AsVal

func (z ZNull) AsVal(ctx Context, t ZType) (Val, error)

func (ZNull) GetType

func (z ZNull) GetType() ZType

func (ZNull) String

func (v ZNull) String() string

func (ZNull) Value

func (z ZNull) Value() Val

func (ZNull) ZVal

func (z ZNull) ZVal() *ZVal

type ZObject

type ZObject interface {
	ZObjectAccess
	Val

	GetOpaque(c ZClass) interface{}
	SetOpaque(c ZClass, v interface{})
	GetClass() ZClass
	NewIterator() ZIterator
	HashTable() *ZHashTable
	Clone(ctx Context) (ZObject, error)
	GetParent() ZObject
	GetKin(className string) ZObject
	IterProps(ctx Context) iter.Seq[*ZClassProp]

	// IncrJsonApplyCount increments the json_encode recursion guard counter.
	// Returns the count before incrementing; if > 0 the object is already
	// being json-encoded.
	IncrJsonApplyCount() int32
	// DecrJsonApplyCount decrements the json_encode recursion guard counter.
	DecrJsonApplyCount()

	// IncrSerializeApplyCount increments the serialize recursion guard counter.
	// Returns the count before incrementing; if > 0 the object is already
	// being serialized.
	IncrSerializeApplyCount() int32
	// DecrSerializeApplyCount decrements the serialize recursion guard counter.
	DecrSerializeApplyCount()
}

type ZObjectAccess

type ZObjectAccess interface {
	ObjectGet(ctx Context, key Val) (*ZVal, error)
	ObjectSet(ctx Context, key Val, value *ZVal) error
}

type ZObjectAttr

type ZObjectAttr int

func (ZObjectAttr) Access

func (a ZObjectAttr) Access() ZObjectAttr

func (ZObjectAttr) Has

func (a ZObjectAttr) Has(c ZObjectAttr) bool

func (ZObjectAttr) IsPrivate

func (a ZObjectAttr) IsPrivate() bool

func (ZObjectAttr) IsProtected

func (a ZObjectAttr) IsProtected() bool

func (ZObjectAttr) IsPublic

func (a ZObjectAttr) IsPublic() bool

func (ZObjectAttr) IsReadonly

func (a ZObjectAttr) IsReadonly() bool

func (ZObjectAttr) IsStatic

func (a ZObjectAttr) IsStatic() bool

type ZString

type ZString string

func (ZString) Array

func (z ZString) Array() ZStringArray

func (ZString) AsNumeric

func (z ZString) AsNumeric() (Val, error)

func (ZString) AsVal

func (z ZString) AsVal(ctx Context, t ZType) (Val, error)

func (ZString) ContainsInvalidNumeric

func (z ZString) ContainsInvalidNumeric() bool

func (ZString) GetType

func (z ZString) GetType() ZType

func (ZString) IsNumeric

func (s ZString) IsNumeric() bool

func (ZString) LooksInt

func (s ZString) LooksInt() bool

func (ZString) String

func (v ZString) String() string

func (ZString) ToLower

func (s ZString) ToLower() ZString

func (ZString) ToUpper

func (s ZString) ToUpper() ZString

func (ZString) Value

func (v ZString) Value() Val

func (ZString) ZVal

func (z ZString) ZVal() *ZVal

type ZStringArray

type ZStringArray struct {
	*ZString
}

func (ZStringArray) OffsetCheck

func (z ZStringArray) OffsetCheck(ctx Context, key Val) (*ZVal, bool, error)

func (ZStringArray) OffsetExists

func (z ZStringArray) OffsetExists(ctx Context, key Val) (bool, error)

func (ZStringArray) OffsetGet

func (z ZStringArray) OffsetGet(ctx Context, key Val) (*ZVal, error)

func (ZStringArray) OffsetSet

func (z ZStringArray) OffsetSet(ctx Context, key Val, value *ZVal) error

func (ZStringArray) OffsetUnset

func (z ZStringArray) OffsetUnset(ctx Context, key Val) error

func (ZStringArray) String

func (z ZStringArray) String() ZString

type ZType

type ZType int
const (
	ZtNull ZType = iota
	ZtBool
	ZtInt
	ZtFloat
	ZtString
	ZtArray
	ZtObject
	ZtResource
	ZtCallable
	ZtMixed // PHP 8.0 mixed type (accepts any value)
	ZtVoid  // PHP 7.1 void return type
	ZtNever // PHP 8.1 never return type
)

func (ZType) String

func (zt ZType) String() string

func (ZType) TypeName

func (zt ZType) TypeName() string

TypeName returns the PHP 8-style type name (lowercase, short form)

type ZVal

type ZVal struct {
	Name *ZString
	// contains filtered or unexported fields
}

ZVal is a pointer to a value, that can be used as a Val, a reference, etc.

Eventually, ZVal will only be used for references.

func CompareObjectToNumeric

func CompareObjectToNumeric(ctx Context, z *ZVal, targetType ZType) *ZVal

compareObjectToNumeric converts an object to a numeric type for comparison, emitting E_NOTICE (not E_WARNING) as PHP does for implicit comparison conversions. targetType should be ZtInt or ZtFloat depending on the other operand.

func MakeZVal

func MakeZVal(v Val) *ZVal

func NewZVal

func NewZVal(v Val) *ZVal

func ZStr

func ZStr(s string) *ZVal

func (*ZVal) AddTypeChecker

func (z *ZVal) AddTypeChecker(fn func(Context, Val) error)

AddTypeChecker attaches a type constraint function to this ZVal. The function is called whenever the ZVal's value is changed via SetWithCtx.

func (*ZVal) Array

func (z *ZVal) Array() ZArrayAccess

func (*ZVal) As

func (z *ZVal) As(ctx Context, t ZType) (*ZVal, error)

func (*ZVal) AsArray

func (z *ZVal) AsArray(ctx Context) *ZArray

func (*ZVal) AsBool

func (z *ZVal) AsBool(ctx Context) ZBool

func (*ZVal) AsFloat

func (z *ZVal) AsFloat(ctx Context) ZFloat

func (*ZVal) AsInt

func (z *ZVal) AsInt(ctx Context) ZInt

func (*ZVal) AsNumeric

func (z *ZVal) AsNumeric(ctx Context) (*ZVal, error)

func (*ZVal) AsObject

func (z *ZVal) AsObject(ctx Context) ZObject

func (*ZVal) AsString

func (z *ZVal) AsString(ctx Context) ZString

func (*ZVal) AsVal

func (z *ZVal) AsVal(ctx Context, t ZType) (Val, error)

func (*ZVal) CastTo

func (z *ZVal) CastTo(ctx Context, t ZType) error

func (*ZVal) Dup

func (z *ZVal) Dup() *ZVal

func (*ZVal) GetName

func (z *ZVal) GetName() ZString

func (*ZVal) GetType

func (z *ZVal) GetType() ZType

func (*ZVal) HasTypeCheckers

func (z *ZVal) HasTypeCheckers() bool

HasTypeCheckers returns true if this ZVal or its referenced inner ZVal has any type constraint checkers registered.

func (*ZVal) HashTable

func (z *ZVal) HashTable() *ZHashTable

func (*ZVal) IsNull

func (z *ZVal) IsNull() bool

func (*ZVal) IsRef

func (z *ZVal) IsRef() bool

func (*ZVal) MakeRef

func (z *ZVal) MakeRef()

MakeRef converts a plain ZVal into a reference in-place by wrapping its current value in an inner ZVal. If already a reference, this is a no-op. This is used when a hash table entry needs to become a reference without going through Set() which has self-reference detection that creates an unwanted double-reference.

func (*ZVal) NewIterator

func (z *ZVal) NewIterator() ZIterator

func (*ZVal) Nude

func (z *ZVal) Nude() *ZVal

Returns actual zval, dropping status of reference

func (*ZVal) Ref

func (z *ZVal) Ref() *ZVal

Ref returns a reference to this zval while making it itself a ref. If z is an inner reference ZVal (has refCount > 0), creating a new wrapper increments the refCount to track the additional alias.

func (*ZVal) RefInner

func (z *ZVal) RefInner() *ZVal

RefInner returns the inner ZVal of a reference and increments its refCount. This should be called when creating a new alias to the inner value (e.g. $this->prop = &$param). Returns nil if not a reference.

func (*ZVal) RefTarget

func (z *ZVal) RefTarget() *ZVal

RefTarget returns the inner ZVal of a reference without incrementing refCount. Used for identity comparison (e.g. serialize() detecting shared references). Returns nil if not a reference.

func (*ZVal) Set

func (z *ZVal) Set(nz *ZVal)

func (*ZVal) SetWithCtx

func (z *ZVal) SetWithCtx(ctx Context, nz *ZVal) error

SetWithCtx sets this ZVal's value (following the reference chain), running any registered type checkers before committing the new value. Returns an error if a type constraint is violated.

func (*ZVal) String

func (z *ZVal) String() string

func (*ZVal) UnRef

func (z *ZVal) UnRef()

UnRef unwraps a reference, replacing the outer ZVal's value with the inner value. This simulates PHP's refcount-based un-ref when refcount drops to 1.

func (*ZVal) UnRefIfAlone

func (z *ZVal) UnRefIfAlone()

UnRefIfAlone unwraps a reference only if the inner ZVal's refCount is <= 1, meaning no other location holds a reference to the same inner value. Used after function calls for compound writable by-ref args.

func (*ZVal) Value

func (z *ZVal) Value() Val

func (*ZVal) ZVal

func (z *ZVal) ZVal() *ZVal

ZVal will make a copy of a given zval without actually copying memory

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL